<template>
  <div class="performance-page" ref="performancePageRef">
    
    
    
    <div class="performance-grid">
             <div v-for="(item, index) in performanceItems" :key="index" 
            :class="['performance-item', { 'fault-deduction': item.key === 'faultDeduction' }]">
        <div class="item-header">
          <div class="title-section">
            <el-tooltip :content="item.name" placement="top" :show-after="500" :hide-after="0">
              <h3>{{ item.name }}</h3>
            </el-tooltip>
            <p v-if="item.description" class="item-description">{{ item.description }}</p>
          </div>
                     <div class="button-group">
           <template v-if="(['product','assignedTask','assignedDelay','developmentDelay','developmentTask','testTask','wikiScore','maintenanceRecord','onlineTestScore','testCaseScore','communication','onlineOperation','requirementScore','workloadScore','reportMaterial','businessTrip','overtime','onlineRollback','inspectionMiss','onlineDelay','onlinePlanCompletion','onlineTaskCompletion','poorDailyReport','dailyReportRepetition'].includes(item.key)) && (performanceAbstract[item.key]?.count ?? 0) > 0">
               <el-button type="warning" size="small" @click="resetPerformance(item.key)"
                 :loading="actionLoading[item.key]?.reset" class="action-btn">
                 重新计算
               </el-button>
               <el-button type="primary" size="small" @click="savePerformance(item.key)"
                 :loading="actionLoading[item.key]?.save" class="action-btn">
                 存为历史数据
               </el-button>
             </template>
             <template v-else-if="item.key !== 'faultDeduction'">
               <el-button type="success" size="small" @click="calculatePerformanceData(item.key)"
                 :loading="calculatingStates[item.key]" class="action-btn">
                 计算
               </el-button>
             </template>
           </div>
        </div>
        
        <!-- 摘要信息（初始化展示） -->
        <div class="abstract-summary">
          <el-descriptions :column="2" border size="small">
            <el-descriptions-item label="数据条数">
              <el-link
                type="primary"
                :underline="false"
               :disabled="!['product','assignedTask','assignedDelay','developmentDelay','developmentTask','testTask','wikiScore','maintenanceRecord','onlineTestScore','testCaseScore','communication','onlineOperation','requirementScore','workloadScore','reportMaterial','businessTrip','overtime','onlineRollback','inspectionMiss','onlineDelay','onlinePlanCompletion','onlineTaskCompletion','poorDailyReport','dailyReportRepetition'].includes(item.key) || (performanceAbstract[item.key]?.count ?? 0) === 0"
                @click="handleClickAbstractCount(item)"
              >
                {{ performanceAbstract[item.key]?.count ?? 0 }}条
              </el-link>
            </el-descriptions-item>
            <el-descriptions-item label="最近计算时间">
              {{ performanceAbstract[item.key]?.latestTime || '暂无数据' }}
            </el-descriptions-item>
          </el-descriptions>
        </div>
        
      </div>
    </div>
  </div>

  <!-- WIKI得分绩效日期选择对话框 -->
  <el-dialog v-model="wikiScoreDateVisible" title="选择WIKI得分绩效计算日期" width="400px" :close-on-click-modal="false" @close="handleWikiScoreDateClose">
    <div class="date-selection">
      <el-date-picker
        v-model="wikiScoreDate"
        type="month"
        placeholder="选择月份"
        format="YYYY-MM"
        value-format="YYYY-MM"
        style="width: 100%"
      />
    </div>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleWikiScoreDateCancel">取消</el-button>
        <el-button type="primary" @click="confirmWikiScoreDate" :loading="wikiScoreDateLoading">确定</el-button>
      </span>
    </template>
  </el-dialog>

  <!-- 上线延期数量绩效日期选择对话框 -->
  <el-dialog v-model="onlineDelayDateVisible" title="选择上线延期数量绩效计算日期" width="400px" :close-on-click-modal="false" @close="handleOnlineDelayDateClose">
    <div class="date-selection">
      <el-date-picker
        v-model="onlineDelayDate"
        type="month"
        placeholder="选择月份"
        format="YYYY-MM"
        value-format="YYYY-MM"
        style="width: 100%"
      />
    </div>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleOnlineDelayDateCancel">取消</el-button>
        <el-button type="primary" @click="confirmOnlineDelayDate" :loading="onlineDelayDateLoading">确定</el-button>
      </span>
    </template>
  </el-dialog>

  <!-- 上线计划达成绩效日期选择对话框 -->
  <el-dialog v-model="onlinePlanCompletionDateVisible" title="选择上线计划达成绩效计算日期" width="400px" :close-on-click-modal="false" @close="handleOnlinePlanCompletionDateClose">
    <div class="date-selection">
      <el-date-picker
        v-model="onlinePlanCompletionDate"
        type="month"
        placeholder="选择月份"
        format="YYYY-MM"
        value-format="YYYY-MM"
        style="width: 100%"
      />
    </div>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleOnlinePlanCompletionDateCancel">取消</el-button>
        <el-button type="primary" @click="confirmOnlinePlanCompletionDate" :loading="onlinePlanCompletionDateLoading">确定</el-button>
      </span>
    </template>
  </el-dialog>

  <!-- 未巡检数量绩效日期选择对话框 -->
  <el-dialog v-model="inspectionMissDateVisible" title="选择未巡检数量绩效计算日期" width="400px" :close-on-click-modal="false" @close="handleInspectionMissDateClose">
    <div class="date-selection">
      <el-date-picker
        v-model="inspectionMissDate"
        type="month"
        placeholder="选择月份"
        format="YYYY-MM"
        value-format="YYYY-MM"
        style="width: 100%"
      />
    </div>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleInspectionMissDateCancel">取消</el-button>
        <el-button type="primary" @click="confirmInspectionMissDate" :loading="inspectionMissDateLoading">确定</el-button>
      </span>
    </template>
  </el-dialog>

  <!-- 上线回退次数绩效日期选择对话框 -->
  <el-dialog v-model="onlineRollbackDateVisible" title="选择上线回退次数绩效计算日期" width="400px" :close-on-click-modal="false" @close="handleOnlineRollbackDateClose">
    <div class="date-selection">
      <el-date-picker
        v-model="onlineRollbackDate"
        type="month"
        placeholder="选择月份"
        format="YYYY-MM"
        value-format="YYYY-MM"
        style="width: 100%"
      />
    </div>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleOnlineRollbackDateCancel">取消</el-button>
        <el-button type="primary" @click="confirmOnlineRollbackDate" :loading="onlineRollbackDateLoading">确定</el-button>
      </span>
    </template>
  </el-dialog>

  <!-- 上线运维及测试任务达成率绩效日期选择对话框 -->
  <el-dialog v-model="onlineTaskCompletionDateVisible" title="选择上线运维及测试任务达成率绩效计算日期" width="400px" :close-on-click-modal="false" @close="handleOnlineTaskCompletionDateClose">
    <div class="date-selection">
      <el-date-picker
        v-model="onlineTaskCompletionDate"
        type="month"
        placeholder="选择月份"
        format="YYYY-MM"
        value-format="YYYY-MM"
        style="width: 100%"
      />
    </div>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleOnlineTaskCompletionDateCancel">取消</el-button>
        <el-button type="primary" @click="confirmOnlineTaskCompletionDate" :loading="onlineTaskCompletionDateLoading">确定</el-button>
      </span>
    </template>
  </el-dialog>

  <!-- 汇报材料得分绩效日期选择对话框 -->
  <el-dialog v-model="reportMaterialScoreDateVisible" title="选择汇报材料得分绩效计算日期" width="400px" :close-on-click-modal="false" @close="handleReportMaterialScoreDateClose">
    <div class="date-selection">
      <el-date-picker
        v-model="reportMaterialScoreDate"
        type="month"
        placeholder="选择月份"
        format="YYYY-MM"
        value-format="YYYY-MM"
        style="width: 100%"
      />
    </div>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleReportMaterialScoreDateCancel">取消</el-button>
        <el-button type="primary" @click="confirmReportMaterialScoreDate" :loading="reportMaterialScoreDateLoading">确定</el-button>
      </span>
    </template>
  </el-dialog>

  <!-- 上线测试得分绩效日期选择对话框 -->
  <el-dialog v-model="onlineTestScoreDateVisible" title="选择上线测试得分绩效计算日期" width="400px" :close-on-click-modal="false" @close="handleOnlineTestScoreDateClose">
    <div class="date-selection">
      <el-date-picker
        v-model="onlineTestScoreDate"
        type="month"
        placeholder="选择月份"
        format="YYYY-MM"
        value-format="YYYY-MM"
        style="width: 100%"
      />
    </div>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleOnlineTestScoreDateCancel">取消</el-button>
        <el-button type="primary" @click="confirmOnlineTestScoreDate" :loading="onlineTestScoreDateLoading">确定</el-button>
      </span>
    </template>
  </el-dialog>

  <!-- 维护记录数量绩效日期选择对话框 -->
  <el-dialog v-model="maintenanceScoreDateVisible" title="选择维护记录数量绩效计算日期" width="400px" :close-on-click-modal="false" @close="handleMaintenanceScoreDateClose">
    <div class="date-selection">
      <el-date-picker
        v-model="maintenanceScoreDate"
        type="month"
        placeholder="选择月份"
        format="YYYY-MM"
        value-format="YYYY-MM"
        style="width: 100%"
      />
    </div>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleMaintenanceScoreDateCancel">取消</el-button>
        <el-button type="primary" @click="confirmMaintenanceScoreDate" :loading="maintenanceScoreDateLoading">确定</el-button>
      </span>
    </template>
  </el-dialog>

  <!-- 用例得分绩效日期选择对话框 -->
  <el-dialog v-model="useCaseScoreDateVisible" title="选择用例得分绩效计算日期" width="400px" :close-on-click-modal="false" @close="handleUseCaseScoreDateClose">
    <div class="date-selection">
      <el-date-picker
        v-model="useCaseScoreDate"
        type="month"
        placeholder="选择月份"
        format="YYYY-MM"
        value-format="YYYY-MM"
        style="width: 100%"
      />
    </div>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleUseCaseScoreDateCancel">取消</el-button>
        <el-button type="primary" @click="confirmUseCaseScoreDate" :loading="useCaseScoreDateLoading">确定</el-button>
      </span>
    </template>
  </el-dialog>

  <!-- 沟通协调得分绩效日期选择对话框 -->
  <el-dialog v-model="communicationScoreDateVisible" title="选择沟通协调得分绩效计算日期" width="400px" :close-on-click-modal="false" @close="handleCommunicationScoreDateClose">
    <div class="date-selection">
      <el-date-picker
        v-model="communicationScoreDate"
        type="month"
        placeholder="选择月份"
        format="YYYY-MM"
        value-format="YYYY-MM"
        style="width: 100%"
      />
    </div>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleCommunicationScoreDateCancel">取消</el-button>
        <el-button type="primary" @click="confirmCommunicationScoreDate" :loading="communicationScoreDateLoading">确定</el-button>
      </span>
    </template>
  </el-dialog>

  <!-- 差的日报绩效日期选择对话框 -->
  <el-dialog v-model="poorDailyReportDateVisible" title="选择差的日报绩效计算日期" width="400px" :close-on-click-modal="false" @close="handlePoorDailyReportDateClose">
    <div class="date-selection">
      <el-date-picker
        v-model="poorDailyReportDate"
        type="month"
        placeholder="选择月份"
        format="YYYY-MM"
        value-format="YYYY-MM"
        style="width: 100%"
      />
    </div>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handlePoorDailyReportDateCancel">取消</el-button>
        <el-button type="primary" @click="confirmPoorDailyReportDate" :loading="poorDailyReportDateLoading">确定</el-button>
      </span>
    </template>
  </el-dialog>

  <!-- 日报重复率绩效日期选择对话框 -->
  <el-dialog v-model="dailyReportRepetitionDateVisible" title="选择日报重复率绩效计算日期" width="400px" :close-on-click-modal="false" @close="handleDailyReportRepetitionDateClose">
    <div class="date-selection">
      <el-date-picker
        v-model="dailyReportRepetitionDate"
        type="month"
        placeholder="选择月份"
        format="YYYY-MM"
        value-format="YYYY-MM"
        style="width: 100%"
      />
    </div>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleDailyReportRepetitionDateCancel">取消</el-button>
        <el-button type="primary" @click="confirmDailyReportRepetitionDate" :loading="dailyReportRepetitionDateLoading">确定</el-button>
      </span>
    </template>
  </el-dialog>

  <!-- 上线运维得分绩效日期选择对话框 -->
  <el-dialog v-model="onlineOperationScoreDateVisible" title="选择上线运维得分绩效计算日期" width="400px" :close-on-click-modal="false" @close="handleOnlineOperationScoreDateClose">
    <div class="date-selection">
      <el-date-picker
        v-model="onlineOperationScoreDate"
        type="month"
        placeholder="选择月份"
        format="YYYY-MM"
        value-format="YYYY-MM"
        style="width: 100%"
      />
    </div>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleOnlineOperationScoreDateCancel">取消</el-button>
        <el-button type="primary" @click="confirmOnlineOperationScoreDate" :loading="onlineOperationScoreDateLoading">确定</el-button>
      </span>
    </template>
  </el-dialog>

  <!-- 工作量得分绩效日期选择对话框 -->
  <el-dialog v-model="workloadScoreDateVisible" title="选择工作量得分绩效计算日期" width="400px" :close-on-click-modal="false" @close="handleWorkloadScoreDateClose">
    <div class="date-selection">
      <el-date-picker
        v-model="workloadScoreDate"
        type="month"
        placeholder="选择月份"
        format="YYYY-MM"
        value-format="YYYY-MM"
        style="width: 100%"
      />
    </div>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleWorkloadScoreDateCancel">取消</el-button>
        <el-button type="primary" @click="confirmWorkloadScoreDate" :loading="workloadScoreDateLoading">确定</el-button>
      </span>
    </template>
  </el-dialog>

  <!-- 出差得分绩效日期选择对话框 -->
  <el-dialog v-model="businessTripScoreDateVisible" title="选择出差得分绩效计算日期" width="400px" :close-on-click-modal="false" @close="handleBusinessTripScoreDateClose">
    <div class="date-selection">
      <el-date-picker
        v-model="businessTripScoreDate"
        type="month"
        placeholder="选择月份"
        format="YYYY-MM"
        value-format="YYYY-MM"
        style="width: 100%"
      />
    </div>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleBusinessTripScoreDateCancel">取消</el-button>
        <el-button type="primary" @click="confirmBusinessTripScoreDate" :loading="businessTripScoreDateLoading">确定</el-button>
      </span>
    </template>
  </el-dialog>

  <!-- 详情数据模态框（产品/分配任务/研发任务/测试任务/WIKI得分） -->
  <el-dialog v-model="detailsVisible" width="50%" :close-on-click-modal="false"
    :close-on-press-escape="true" class="performance-dialog">
    <div v-if="performanceData[currentDetailType] && performanceData[currentDetailType].rawData">
      <div class="dialog-header">
        <h3>{{ currentDetailTitle }} (共{{ performanceData[currentDetailType].rawData.length }}条)</h3>
        <div class="dialog-actions">
          <el-input
            v-model="keyword"
            size="small"
            placeholder="搜索姓名"
            clearable
            class="toolbar-input"
          />
          <el-switch
            v-model="showTopTen"
            active-text="只看前10名"
            class="toolbar-switch"
            size="small"
          />
          <el-button type="primary" size="small" @click="exportPerformanceData">
            导出数据
          </el-button>
        </div>
      </div>
      <el-table
        v-if="performanceData[currentDetailType] && performanceData[currentDetailType].rawData"
        :data="detailTableData"
        border
        stripe
        highlight-current-row
        :max-height="tableMaxHeight"
        v-loading="detailsLoading"
        :row-class-name="rowClassName"
        class="product-performance-table"
      >
        <el-table-column type="index" label="#" width="60" align="center" />
        <el-table-column prop="versionPost" label="绩效岗位"  min-width="120" />
        <el-table-column label="用户姓名" min-width="180" sortable>
          <template #default="{ row }">
            <span class="name-highlight">{{ row.userName }}</span>
            <el-tag
              v-if="row.scoreRank"
              size="small"
              effect="light"
              :type="getRankTagType(row.scoreRank)"
              class="rank-tag"
            >
              第{{ row.scoreRank }}名
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="rankScore" label="绩效得分" align="center" width="160" sortable />
        <el-table-column prop="score" label="任务得分" align="center" width="160" sortable />
      </el-table>
    </div>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="detailsVisible = false">关闭</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, onUnmounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  calculatePerformanceData as calculatePerformanceAPI,
  GetSummaryPerformanceRequirement,
  GetGetSummaryPerformanceRequirement,
  GetAllPerformanceAbstractRequirement,
  GetResetSummaryPerformanceRequirement,
  GetSaveSummaryPerformanceRequirement,
  summaryAssignmentScore,
  getSummaryAssignmentScore,
  resetSummaryAssignmentScore,
  saveSummaryAssignmentScore,
  summaryDevelopmentScore,
  getSummaryDevelopmentScore,
  resetSummaryDevelopmentScore,
  saveSummaryDevelopmentScore,
  summaryTestingScore,
  getSummaryTestingScore,
  resetSummaryTestingScore,
  saveSummaryTestingScore,
  summaryWikiScore,
  getSummaryWikiScore,
  resetSummaryWikiScore,
  saveSummaryWikiScore,
  summaryMaintenanceScore,
  getSummaryMaintenanceScore,
  resetSummaryMaintenanceScore,
  saveSummaryMaintenanceScore,
  summaryOnlineTestingScore,
  getSummaryOnlineTestingScore,
  resetSummaryOnlineTestingScore,
  saveSummaryOnlineTestingScore,
  summaryUseCaseScore,
  getSummaryUseCaseScore,
  resetSummaryUseCaseScore,
  saveSummaryUseCaseScore,
  summaryCommunicationScore,
  getSummaryCommunicationScore,
  resetSummaryCommunicationScore,
  saveSummaryCommunicationScore,
  summaryOnlineOperationScore,
  getSummaryOnlineOperationScore,
  resetOnlineOperationScore,
  saveSummaryOnlineOperationScore,
  summaryRequirementScore,
  getSummaryRequirementScore,
  resetSummaryRequirementScore,
  saveSummaryRequirementScore,
  summaryWorkloadScore,
  getSummaryWorkloadScore,
  resetSummaryWorkloadScore,
  saveSummaryWorkloadScore,
  summaryReportMaterialScore,
  getSummaryReportMaterialScore,
  resetSummaryReportMaterialScore,
  saveSummaryReportMaterialScore
  ,summaryBusinessTripScore
  ,getSummaryBusinessTripScore
  ,resetSummaryBusinessTripScore
  ,saveSummaryBusinessTripScore
  ,summaryNetOvertimeHoursScore
  ,getSummaryNetOvertimeHoursScore
  ,resetSummaryNetOvertimeHoursScore
  ,saveSummaryNetOvertimeHoursScore
  ,summaryAssignmentDelayTasksScore
  ,getSummaryAssignmentDelayTasksScore
  ,resetSummaryAssignmentDelayTasksScore
  ,saveSummaryAssignmentDelayTasksScore
  ,summaryDevelopmentDelayTasksScore
  ,getSummaryDevelopmentDelayTasksScore
  ,resetSummaryDevelopmentDelayTasksScore
  ,saveSummaryDevelopmentDelayTasksScore
  ,summaryOnlineRollbackCountScore
  ,getSummaryOnlineRollbackCountScore
  ,resetSummaryOnlineRollbackCountScore
  ,saveSummaryOnlineRollbackCountScore
  ,summaryItemUninspectedCountScore
  ,getSummaryItemUninspectedCountScore
  ,resetSummaryItemUninspectedCountScore
  ,saveSummaryItemUninspectedCountScore
  ,summaryItemOnlineDelayCount
  ,getSummaryItemOnlineDelayCount
  ,resetSummaryItemOnlineDelayCount
  ,saveSummaryItemOnlineDelayCount
  ,summaryItemOnlinePlanCompletionRate
  ,getSummaryItemOnlinePlanCompletionRate
  ,resetSummaryItemOnlinePlanCompletionRate
  ,saveSummaryItemOnlinePlanCompletionRate
  ,summaryItemOnlineOperationTasks
  ,getSummaryItemOnlineOperationTasks
  ,resetSummaryItemOnlineOperationTasks
  ,saveSummaryItemOnlineOperationTasks
  ,summaryItemPoorDailyReports
  ,getSummaryItemPoorDailyReports
  ,resetSummaryItemPoorDailyReports
  ,saveSummaryItemPoorDailyReports
  ,summaryItemDailyReportRepetitionRate
  ,getSummaryItemDailyReportRepetitionRate
  ,resetSummaryItemDailyReportRepetitionRate
  ,saveSummaryItemDailyReportRepetitionRate
} from '@/api/performance'

// 绩效项目列表
const performanceItems = ref([
  { name: '产品绩效', key: 'product' },
  { name: '分配任务绩效', key: 'assignedTask' },
  { name: '研发任务绩效', key: 'developmentTask' },
  { name: '测试任务绩效', key: 'testTask' },
  { name: 'WIKI得分绩效', key: 'wikiScore' },
  { name: '维护记录数量绩效', key: 'maintenanceRecord' },
  { name: '上线测试得分绩效', key: 'onlineTestScore' },
  { name: '用例得分绩效', key: 'testCaseScore' },
  { name: '上线运维得分绩效', key: 'onlineOperation' },
  { name: '沟通协调得分绩效', key: 'communication' },
  { name: '需求得分绩效', key: 'requirementScore' },
  { name: '工作量得分绩效', key: 'workloadScore' },
  { name: '汇报材料得分绩效', key: 'reportMaterial' },
  { name: '上线运维及测试任务达成率绩效', key: 'onlineTaskCompletion' },
  { name: '差的日报绩效', key: 'poorDailyReport' },
  { name: '出差绩效', key: 'businessTrip' },
  { name: '净加班绩效', key: 'overtime' },
  { name: '故障评估扣分', key: 'faultDeduction', description: '最终绩效会直接扣除，无需计算' },
  { name: '分配延期绩效', key: 'assignedDelay' },
  { name: '研发延期任务绩效', key: 'developmentDelay' },
  { name: '上线回退次数绩效', key: 'onlineRollback' },
  { name: '未巡检数量绩效', key: 'inspectionMiss' },
  { name: '上线延期数量绩效', key: 'onlineDelay' },
  { name: '上线计划达成绩效', key: 'onlinePlanCompletion' },
  { name: '日报重复率绩效', key: 'dailyReportRepetition' }
])

// 加载状态
const calculatingStates = reactive<Record<string, boolean>>({})
// 顶部批量操作已移除

// 详情模态框状态
const detailsVisible = ref(false)
const currentDetailType = ref<'product' | 'assignedTask' | 'assignedDelay' | 'developmentDelay' | 'developmentTask' | 'testTask' | 'wikiScore' | 'maintenanceRecord' | 'onlineTestScore' | 'testCaseScore' | 'communication' | 'onlineOperation' | 'requirementScore' | 'workloadScore' | 'onlineRollback' | 'inspectionMiss' | 'onlineDelay' | 'onlinePlanCompletion' | 'onlineTaskCompletion'>('product')
const tableMaxHeight = ref(0)
const detailsLoading = ref(false)
const keyword = ref('')
const showTopTen = ref(false)

// WIKI得分绩效日期选择
const wikiScoreDate = ref('')
const wikiScoreDateVisible = ref(false)
const wikiScoreDateLoading = ref(false)

// 维护记录数量绩效日期选择
const maintenanceScoreDate = ref('')
const maintenanceScoreDateVisible = ref(false)
const maintenanceScoreDateLoading = ref(false)

// 上线测试得分绩效日期选择
const onlineTestScoreDate = ref('')
const onlineTestScoreDateVisible = ref(false)
const onlineTestScoreDateLoading = ref(false)

// 用例得分绩效日期选择
const useCaseScoreDate = ref('')
const useCaseScoreDateVisible = ref(false)
const useCaseScoreDateLoading = ref(false)

// 沟通协调得分绩效日期选择
const communicationScoreDate = ref('')
const communicationScoreDateVisible = ref(false)
const communicationScoreDateLoading = ref(false)

// 差的日报绩效日期选择
const poorDailyReportDate = ref('')
const poorDailyReportDateVisible = ref(false)
const poorDailyReportDateLoading = ref(false)

// 日报重复率绩效日期选择
const dailyReportRepetitionDate = ref('')
const dailyReportRepetitionDateVisible = ref(false)
const dailyReportRepetitionDateLoading = ref(false)

// 上线运维得分绩效日期选择
const onlineOperationScoreDate = ref('')
const onlineOperationScoreDateVisible = ref(false)
const onlineOperationScoreDateLoading = ref(false)

// 上线运维及测试任务达成率绩效日期选择
const onlineTaskCompletionDate = ref('')
const onlineTaskCompletionDateVisible = ref(false)
const onlineTaskCompletionDateLoading = ref(false)

// 上线计划达成绩效日期选择
const onlinePlanCompletionDate = ref('')
const onlinePlanCompletionDateVisible = ref(false)
const onlinePlanCompletionDateLoading = ref(false)

// 上线回退次数绩效日期选择
const onlineRollbackDate = ref('')
const onlineRollbackDateVisible = ref(false)
const onlineRollbackDateLoading = ref(false)

// 未巡检数量绩效日期选择
const inspectionMissDate = ref('')
const inspectionMissDateVisible = ref(false)
const inspectionMissDateLoading = ref(false)

// 上线延期数量绩效日期选择
const onlineDelayDate = ref('')
const onlineDelayDateVisible = ref(false)
const onlineDelayDateLoading = ref(false)

// 上线延期数量绩效：月份选择处理
const handleOnlineDelayDateCancel = () => {
  onlineDelayDateVisible.value = false
  calculatingStates['onlineDelay'] = false
  if (actionLoading['onlineDelay']?.reset) {
    actionLoading['onlineDelay'].reset = false
  }
}

const handleOnlineDelayDateClose = () => {
  calculatingStates['onlineDelay'] = false
  if (actionLoading['onlineDelay']?.reset) {
    actionLoading['onlineDelay'].reset = false
  }
}

const confirmOnlineDelayDate = async () => {
  if (!onlineDelayDate.value) {
    ElMessage.warning('请选择计算日期')
    return
  }
  onlineDelayDateLoading.value = true
  try {
    const isReset = actionLoading['onlineDelay']?.reset
    const result = isReset
      ? await resetSummaryItemOnlineDelayCount(onlineDelayDate.value)
      : await summaryItemOnlineDelayCount(onlineDelayDate.value)
    if (result.data.code === 200) {
      await new Promise(resolve => setTimeout(resolve, 1000))
      await fetchOnlineDelayPerformanceData()
      await fetchAllPerformanceAbstract()
      ElMessage.success(`上线延期数量绩效${isReset ? '重新计算' : '计算'}完成`)
      onlineDelayDateVisible.value = false
    } else {
      ElMessage.error(result.data.msg || `${isReset ? '重新计算' : '计算'}失败`)
    }
  } catch (error) {
    ElMessage.error(`${actionLoading['onlineDelay']?.reset ? '重新计算' : '计算'}失败`)
  } finally {
    onlineDelayDateLoading.value = false
    calculatingStates['onlineDelay'] = false
    if (actionLoading['onlineDelay']?.reset) {
      actionLoading['onlineDelay'].reset = false
    }
  }
}

// 工作量得分绩效日期选择
const workloadScoreDate = ref('')
const workloadScoreDateVisible = ref(false)
const workloadScoreDateLoading = ref(false)

// 汇报材料得分绩效日期选择
const reportMaterialScoreDate = ref('')
const reportMaterialScoreDateVisible = ref(false)
const reportMaterialScoreDateLoading = ref(false)

// 出差得分绩效日期选择
const businessTripScoreDate = ref('')
const businessTripScoreDateVisible = ref(false)
const businessTripScoreDateLoading = ref(false)

// 滚动相关
const performancePageRef = ref<HTMLElement>()

// 处理未巡检数量绩效日期选择取消
const handleInspectionMissDateCancel = () => {
  inspectionMissDateVisible.value = false
  calculatingStates['inspectionMiss'] = false
  if (actionLoading['inspectionMiss']?.reset) {
    actionLoading['inspectionMiss'].reset = false
  }
}

// 处理未巡检数量绩效日期选择对话框关闭
const handleInspectionMissDateClose = () => {
  calculatingStates['inspectionMiss'] = false
  if (actionLoading['inspectionMiss']?.reset) {
    actionLoading['inspectionMiss'].reset = false
  }
}

// 确认未巡检数量绩效日期选择
const confirmInspectionMissDate = async () => {
  if (!inspectionMissDate.value) {
    ElMessage.warning('请选择计算日期')
    return
  }
  inspectionMissDateLoading.value = true
  try {
    const isReset = actionLoading['inspectionMiss']?.reset
    const result = isReset
      ? await resetSummaryItemUninspectedCountScore(inspectionMissDate.value)
      : await summaryItemUninspectedCountScore(inspectionMissDate.value)
    if (result.data.code === 200) {
      await new Promise(resolve => setTimeout(resolve, 1000))
      await fetchInspectionMissPerformanceData()
      await fetchAllPerformanceAbstract()
      ElMessage.success(`未巡检数量绩效${isReset ? '重新计算' : '计算'}完成`)
      inspectionMissDateVisible.value = false
    } else {
      ElMessage.error(result.data.msg || `${isReset ? '重新计算' : '计算'}失败`)
    }
  } catch (error) {
    ElMessage.error(`${actionLoading['inspectionMiss']?.reset ? '重新计算' : '计算'}失败`)
  } finally {
    inspectionMissDateLoading.value = false
    calculatingStates['inspectionMiss'] = false
    if (actionLoading['inspectionMiss']?.reset) {
      actionLoading['inspectionMiss'].reset = false
    }
  }
}

const detailTableData = computed(() => {
  const rows = performanceData[currentDetailType.value]?.rawData || []
  const byKeyword = keyword.value
    ? rows.filter((r: any) => String(r.userName || '').includes(keyword.value))
    : rows
  const sorted = [...byKeyword].sort((a: any, b: any) => {
    const ra = a.scoreRank ?? Number.MAX_SAFE_INTEGER
    const rb = b.scoreRank ?? Number.MAX_SAFE_INTEGER
    return ra - rb
  })
  return showTopTen.value ? sorted.slice(0, 10) : sorted
})

// 绩效数据
const performanceData = reactive<Record<string, any>>({})
// 各绩效类型摘要信息
const performanceAbstract = reactive<Record<string, { count: number; latestTime: string }>>({})

// 操作按钮加载状态（产品/分配/分配延期/研发延期/研发/测试/WIKI/维护记录/上线测试得分/用例得分/沟通协调得分/差的日报绩效/日报重复率绩效/上线运维得分/工作量得分）
const actionLoading = reactive<Record<string, { reset: boolean; save: boolean }>>({
  product: { reset: false, save: false },
  assignedTask: { reset: false, save: false },
  assignedDelay: { reset: false, save: false },
  developmentDelay: { reset: false, save: false },
  developmentTask: { reset: false, save: false },
  testTask: { reset: false, save: false },
  wikiScore: { reset: false, save: false },
  maintenanceRecord: { reset: false, save: false },
  onlineTestScore: { reset: false, save: false },
  testCaseScore: { reset: false, save: false },
  communication: { reset: false, save: false },
  onlineOperation: { reset: false, save: false },
  requirementScore: { reset: false, save: false },
  workloadScore: { reset: false, save: false },
  reportMaterial: { reset: false, save: false },
  businessTrip: { reset: false, save: false },
  overtime: { reset: false, save: false },
  onlineRollback: { reset: false, save: false },
  inspectionMiss: { reset: false, save: false },
  onlineDelay: { reset: false, save: false }
  ,onlinePlanCompletion: { reset: false, save: false }
  ,onlineTaskCompletion: { reset: false, save: false }
  ,poorDailyReport: { reset: false, save: false }
  ,dailyReportRepetition: { reset: false, save: false }
})

// 获取所有绩效摘要信息
const fetchAllPerformanceAbstract = async () => {
  try {
    const res = await GetAllPerformanceAbstractRequirement()
    // 先重置为0，保证接口返回空时页面也能清零并切换按钮
    performanceItems.value.forEach((p) => {
      performanceAbstract[p.key] = { count: 0, latestTime: '' }
    })
    if (res.data && res.data.code === 200 && Array.isArray(res.data.data)) {
      const list = res.data.data as Array<any>
      list.forEach((it) => {
        const matched = performanceItems.value.find(p => p.name === it.level_type)
        if (matched) {
          performanceAbstract[matched.key] = {
            count: typeof it.count === 'number' ? it.count : 0,
            latestTime: it.latest_time || ''
          }
        }
      })
    }
  } catch (error) {
    // 静默处理
  }
}
// 处理上线运维及测试任务达成率绩效日期选择取消
const handleOnlineTaskCompletionDateCancel = () => {
  onlineTaskCompletionDateVisible.value = false
  // 重置加载状态
  calculatingStates['onlineTaskCompletion'] = false
  if (actionLoading['onlineTaskCompletion']?.reset) {
    actionLoading['onlineTaskCompletion'].reset = false
  }
}

// 处理上线计划达成绩效日期选择取消
const handleOnlinePlanCompletionDateCancel = () => {
  onlinePlanCompletionDateVisible.value = false
  calculatingStates['onlinePlanCompletion'] = false
  if (actionLoading['onlinePlanCompletion']?.reset) {
    actionLoading['onlinePlanCompletion'].reset = false
  }
}

// 处理上线回退次数绩效日期选择取消
const handleOnlineRollbackDateCancel = () => {
  onlineRollbackDateVisible.value = false
  calculatingStates['onlineRollback'] = false
  if (actionLoading['onlineRollback']?.reset) {
    actionLoading['onlineRollback'].reset = false
  }
}

// 处理上线回退次数绩效日期选择对话框关闭
const handleOnlineRollbackDateClose = () => {
  calculatingStates['onlineRollback'] = false
  if (actionLoading['onlineRollback']?.reset) {
    actionLoading['onlineRollback'].reset = false
  }
}

// 确认上线回退次数绩效日期选择
const confirmOnlineRollbackDate = async () => {
  if (!onlineRollbackDate.value) {
    ElMessage.warning('请选择计算日期')
    return
  }
  onlineRollbackDateLoading.value = true
  try {
    const isReset = actionLoading['onlineRollback']?.reset
    const result = isReset
      ? await resetSummaryOnlineRollbackCountScore(onlineRollbackDate.value)
      : await summaryOnlineRollbackCountScore(onlineRollbackDate.value)
    if (result.data.code === 200) {
      await new Promise(resolve => setTimeout(resolve, 1000))
      await fetchOnlineRollbackPerformanceData()
      await fetchAllPerformanceAbstract()
      ElMessage.success(`上线回退次数绩效${isReset ? '重新计算' : '计算'}完成`)
      onlineRollbackDateVisible.value = false
    } else {
      ElMessage.error(result.data.msg || `${isReset ? '重新计算' : '计算'}失败`)
    }
  } catch (error) {
    ElMessage.error(`${actionLoading['onlineRollback']?.reset ? '重新计算' : '计算'}失败`)
  } finally {
    onlineRollbackDateLoading.value = false
    calculatingStates['onlineRollback'] = false
    if (actionLoading['onlineRollback']?.reset) {
      actionLoading['onlineRollback'].reset = false
    }
  }
}
// 处理上线运维及测试任务达成率绩效日期选择对话框关闭
const handleOnlineTaskCompletionDateClose = () => {
  calculatingStates['onlineTaskCompletion'] = false
  if (actionLoading['onlineTaskCompletion']?.reset) {
    actionLoading['onlineTaskCompletion'].reset = false
  }
}

// 处理上线计划达成绩效日期选择对话框关闭
const handleOnlinePlanCompletionDateClose = () => {
  calculatingStates['onlinePlanCompletion'] = false
  if (actionLoading['onlinePlanCompletion']?.reset) {
    actionLoading['onlinePlanCompletion'].reset = false
  }
}

// 确认上线运维及测试任务达成率绩效日期选择
const confirmOnlineTaskCompletionDate = async () => {
  if (!onlineTaskCompletionDate.value) {
    ElMessage.warning('请选择计算日期')
    return
  }
  onlineTaskCompletionDateLoading.value = true
  try {
    const isReset = actionLoading['onlineTaskCompletion']?.reset
    const result = isReset
      ? await resetSummaryItemOnlineOperationTasks(onlineTaskCompletionDate.value)
      : await summaryItemOnlineOperationTasks(onlineTaskCompletionDate.value)
    if (result.data.code === 200) {
      await new Promise(resolve => setTimeout(resolve, 1000))
      await fetchOnlineTaskCompletionPerformanceData()
      await fetchAllPerformanceAbstract()
      ElMessage.success(`上线运维及测试任务达成率绩效${isReset ? '重新计算' : '计算'}完成`)
      onlineTaskCompletionDateVisible.value = false
    } else {
      ElMessage.error(result.data.msg || `${isReset ? '重新计算' : '计算'}失败`)
    }
  } catch (error) {
    ElMessage.error(`${actionLoading['onlineTaskCompletion']?.reset ? '重新计算' : '计算'}失败`)
  } finally {
    onlineTaskCompletionDateLoading.value = false
    calculatingStates['onlineTaskCompletion'] = false
    if (actionLoading['onlineTaskCompletion']?.reset) {
      actionLoading['onlineTaskCompletion'].reset = false
    }
  }
}

// 确认上线计划达成绩效日期选择
const confirmOnlinePlanCompletionDate = async () => {
  if (!onlinePlanCompletionDate.value) {
    ElMessage.warning('请选择计算日期')
    return
  }
  onlinePlanCompletionDateLoading.value = true
  try {
    const isReset = actionLoading['onlinePlanCompletion']?.reset
    const result = isReset
      ? await resetSummaryItemOnlinePlanCompletionRate(onlinePlanCompletionDate.value)
      : await summaryItemOnlinePlanCompletionRate(onlinePlanCompletionDate.value)
    if (result.data.code === 200) {
      await new Promise(resolve => setTimeout(resolve, 1000))
      await fetchOnlinePlanCompletionPerformanceData()
      await fetchAllPerformanceAbstract()
      ElMessage.success(`上线计划达成绩效${isReset ? '重新计算' : '计算'}完成`)
      onlinePlanCompletionDateVisible.value = false
    } else {
      ElMessage.error(result.data.msg || `${isReset ? '重新计算' : '计算'}失败`)
    }
  } catch (error) {
    ElMessage.error(`${actionLoading['onlinePlanCompletion']?.reset ? '重新计算' : '计算'}失败`)
  } finally {
    onlinePlanCompletionDateLoading.value = false
    calculatingStates['onlinePlanCompletion'] = false
    if (actionLoading['onlinePlanCompletion']?.reset) {
      actionLoading['onlinePlanCompletion'].reset = false
    }
  }
}



// 确保页面可以滚动
const ensureScrollable = () => {
  if (performancePageRef.value) {
    // 确保容器可以滚动
    const element = performancePageRef.value
    element.style.overflowY = 'auto'
    element.style.height = '100vh'
  }
}

onMounted(() => {
  ;(async () => {
    await fetchAllPerformanceAbstract()
    if ((performanceAbstract['product']?.count ?? 0) > 0 && !performanceData['product']?.rawData) {
      await fetchProductPerformanceData()
    }
    if ((performanceAbstract['assignedTask']?.count ?? 0) > 0 && !performanceData['assignedTask']?.rawData) {
      await fetchAssignedPerformanceData()
    }
    if ((performanceAbstract['assignedDelay']?.count ?? 0) > 0 && !performanceData['assignedDelay']?.rawData) {
      await fetchAssignedDelayPerformanceData()
    }
    if ((performanceAbstract['developmentDelay']?.count ?? 0) > 0 && !performanceData['developmentDelay']?.rawData) {
      await fetchDevelopmentDelayPerformanceData()
    }
    if ((performanceAbstract['onlineRollback']?.count ?? 0) > 0 && !performanceData['onlineRollback']?.rawData) {
      await fetchOnlineRollbackPerformanceData()
    }
    if ((performanceAbstract['inspectionMiss']?.count ?? 0) > 0 && !performanceData['inspectionMiss']?.rawData) {
      await fetchInspectionMissPerformanceData()
    }
    if ((performanceAbstract['onlineDelay']?.count ?? 0) > 0 && !performanceData['onlineDelay']?.rawData) {
      await fetchOnlineDelayPerformanceData()
    }
    if ((performanceAbstract['onlinePlanCompletion']?.count ?? 0) > 0 && !performanceData['onlinePlanCompletion']?.rawData) {
      await fetchOnlinePlanCompletionPerformanceData()
    }
    if ((performanceAbstract['onlineTaskCompletion']?.count ?? 0) > 0 && !performanceData['onlineTaskCompletion']?.rawData) {
      await fetchOnlineTaskCompletionPerformanceData()
    }
    if ((performanceAbstract['developmentTask']?.count ?? 0) > 0 && !performanceData['developmentTask']?.rawData) {
      await fetchDevelopmentPerformanceData()
    }
    if ((performanceAbstract['testTask']?.count ?? 0) > 0 && !performanceData['testTask']?.rawData) {
      await fetchTestingPerformanceData()
    }
    if ((performanceAbstract['wikiScore']?.count ?? 0) > 0 && !performanceData['wikiScore']?.rawData) {
      await fetchWikiPerformanceData()
    }
    if ((performanceAbstract['maintenanceRecord']?.count ?? 0) > 0 && !performanceData['maintenanceRecord']?.rawData) {
      await fetchMaintenancePerformanceData()
    }
    if ((performanceAbstract['onlineTestScore']?.count ?? 0) > 0 && !performanceData['onlineTestScore']?.rawData) {
      await fetchOnlineTestPerformanceData()
    }
    if ((performanceAbstract['testCaseScore']?.count ?? 0) > 0 && !performanceData['testCaseScore']?.rawData) {
      await fetchUseCasePerformanceData()
    }
    if ((performanceAbstract['communication']?.count ?? 0) > 0 && !performanceData['communication']?.rawData) {
      await fetchCommunicationPerformanceData()
    }
    if ((performanceAbstract['onlineOperation']?.count ?? 0) > 0 && !performanceData['onlineOperation']?.rawData) {
      await fetchOnlineOperationPerformanceData()
    }
    if ((performanceAbstract['requirementScore']?.count ?? 0) > 0 && !performanceData['requirementScore']?.rawData) {
      await fetchRequirementPerformanceData()
    }
    if ((performanceAbstract['workloadScore']?.count ?? 0) > 0 && !performanceData['workloadScore']?.rawData) {
      await fetchWorkloadPerformanceData()
    }
    if ((performanceAbstract['reportMaterial']?.count ?? 0) > 0 && !performanceData['reportMaterial']?.rawData) {
      await fetchReportMaterialPerformanceData()
    }
    if ((performanceAbstract['businessTrip']?.count ?? 0) > 0 && !performanceData['businessTrip']?.rawData) {
      await fetchBusinessTripPerformanceData()
    }
    if ((performanceAbstract['overtime']?.count ?? 0) > 0 && !performanceData['overtime']?.rawData) {
      await fetchNetOvertimePerformanceData()
    }
  })()
  const updateHeight = () => {
    tableMaxHeight.value = Math.round(window.innerHeight * 0.6)
  }
  updateHeight()
  window.addEventListener('resize', updateHeight)
  
  // 确保页面可以滚动
  setTimeout(() => {
    ensureScrollable() // 确保页面可滚动
  }, 1000)
  
  ;(onUnmounted as any)(() => {
    window.removeEventListener('resize', updateHeight)
  })
})

// 排名相关样式函数已移除（列精简后不再需要）

// 摘要数量点击：打开详细数据模态框（必要时先拉取数据）
const handleClickAbstractCount = async (item: { key: string; name: string }) => {
  if (!['product','assignedTask','assignedDelay','developmentDelay','developmentTask','testTask','wikiScore','maintenanceRecord','onlineTestScore','testCaseScore','communication','onlineOperation','requirementScore','workloadScore','reportMaterial','businessTrip','overtime','onlineRollback','inspectionMiss','onlineDelay','onlinePlanCompletion','onlineTaskCompletion','poorDailyReport','dailyReportRepetition'].includes(item.key)) return
  currentDetailType.value = item.key as any
  if (item.key === 'product') {
    await fetchProductPerformanceData()
  } else if (item.key === 'assignedTask') {
    await fetchAssignedPerformanceData()
  } else if (item.key === 'assignedDelay') {
    await fetchAssignedDelayPerformanceData()
  } else if (item.key === 'developmentDelay') {
    await fetchDevelopmentDelayPerformanceData()
  } else if (item.key === 'onlineRollback') {
    await fetchOnlineRollbackPerformanceData()
  } else if (item.key === 'inspectionMiss') {
    await fetchInspectionMissPerformanceData()
  } else if (item.key === 'onlineDelay') {
    await fetchOnlineDelayPerformanceData()
  } else if (item.key === 'onlinePlanCompletion') {
    await fetchOnlinePlanCompletionPerformanceData()
  } else if (item.key === 'onlineTaskCompletion') {
    await fetchOnlineTaskCompletionPerformanceData()
  } else if (item.key === 'developmentTask') {
    await fetchDevelopmentPerformanceData()
  } else if (item.key === 'testTask') {
    await fetchTestingPerformanceData()
  } else if (item.key === 'wikiScore') {
    await fetchWikiPerformanceData()
  } else if (item.key === 'maintenanceRecord') {
    await fetchMaintenancePerformanceData()
  } else if (item.key === 'onlineTestScore') {
    await fetchOnlineTestPerformanceData()
  } else if (item.key === 'testCaseScore') {
    await fetchUseCasePerformanceData()
  } else if (item.key === 'communication') {
    await fetchCommunicationPerformanceData()
  } else if (item.key === 'poorDailyReport') {
    await fetchPoorDailyReportPerformanceData()
  } else if (item.key === 'dailyReportRepetition') {
    await fetchDailyReportRepetitionPerformanceData()
  } else if (item.key === 'onlineOperation') {
    await fetchOnlineOperationPerformanceData()
  } else if (item.key === 'requirementScore') {
    await fetchRequirementPerformanceData()
  } else if (item.key === 'workloadScore') {
    await fetchWorkloadPerformanceData()
  } else if (item.key === 'reportMaterial') {
    await fetchReportMaterialPerformanceData()
  } else if (item.key === 'businessTrip') {
    await fetchBusinessTripPerformanceData()
  } else if (item.key === 'overtime') {
    await fetchNetOvertimePerformanceData()
  }
  if (performanceData[currentDetailType.value]?.rawData) {
    showDetails()
  } else {
    ElMessage.warning('暂无详细数据')
  }
}

// 统计面板已移除

// 计算绩效数据
const calculatePerformanceData = async (key: string) => {
  calculatingStates[key] = true

  try {
    let response
    // 产品/分配任务/研发任务/测试任务/WIKI得分绩效使用特殊的汇总接口
    if (key === 'product') {
      const result = await GetSummaryPerformanceRequirement()
      if (result.data.code === 200) {
        // 等待一下让后端数据处理完成
        await new Promise(resolve => setTimeout(resolve, 1000))
        // 计算成功后，获取计算后的产品绩效数据
        await fetchProductPerformanceData()
        // 刷新摘要信息
        await fetchAllPerformanceAbstract()
        ElMessage.success(`${performanceItems.value.find(item => item.key === key)?.name}计算完成`)
      } else {
        ElMessage.error(result.data.msg || '计算失败')
      }
    } else if (key === 'assignedTask') {
      const result = await summaryAssignmentScore()
      if (result.data.code === 200) {
        // 等待一下让后端数据处理完成
        await new Promise(resolve => setTimeout(resolve, 1000))
        await fetchAssignedPerformanceData()
        await fetchAllPerformanceAbstract()
        ElMessage.success(`${performanceItems.value.find(item => item.key === key)?.name}计算完成`)
      } else {
        ElMessage.error(result.data.msg || '计算失败')
      }
    } else if (key === 'assignedDelay') {
      const result = await summaryAssignmentDelayTasksScore()
      if (result.data.code === 200) {
        // 等待一下让后端数据处理完成
        await new Promise(resolve => setTimeout(resolve, 1000))
        await fetchAssignedDelayPerformanceData()
        await fetchAllPerformanceAbstract()
        ElMessage.success(`${performanceItems.value.find(item => item.key === key)?.name}计算完成`)
      } else {
        ElMessage.error(result.data.msg || '计算失败')
      }
    } else if (key === 'developmentDelay') {
      const result = await summaryDevelopmentDelayTasksScore()
      if (result.data.code === 200) {
        // 等待一下让后端数据处理完成
        await new Promise(resolve => setTimeout(resolve, 1000))
        await fetchDevelopmentDelayPerformanceData()
        await fetchAllPerformanceAbstract()
        ElMessage.success(`${performanceItems.value.find(item => item.key === key)?.name}计算完成`)
      } else {
        ElMessage.error(result.data.msg || '计算失败')
      }
    } else if (key === 'onlineRollback') {
      // 需要选择月份
      onlineRollbackDate.value = ''
      onlineRollbackDateVisible.value = true
      return
    } else if (key === 'inspectionMiss') {
      // 需要选择月份
      inspectionMissDate.value = ''
      inspectionMissDateVisible.value = true
      return
    } else if (key === 'onlineDelay') {
      // 需要选择月份
      onlineDelayDate.value = ''
      onlineDelayDateVisible.value = true
      return
    } else if (key === 'onlinePlanCompletion') {
      // 需要选择月份
      onlinePlanCompletionDate.value = ''
      onlinePlanCompletionDateVisible.value = true
      return
    } else if (key === 'onlineTaskCompletion') {
      // 需要选择月份
      onlineTaskCompletionDate.value = ''
      onlineTaskCompletionDateVisible.value = true
      return
    } else if (key === 'developmentTask') {
      const result = await summaryDevelopmentScore()
      if (result.data.code === 200) {
        // 等待一下让后端数据处理完成
        await new Promise(resolve => setTimeout(resolve, 1000))
        await fetchDevelopmentPerformanceData()
        await fetchAllPerformanceAbstract()
        ElMessage.success(`${performanceItems.value.find(item => item.key === key)?.name}计算完成`)
      } else {
        ElMessage.error(result.data.msg || '计算失败')
      }
    } else if (key === 'testTask') {
      const result = await summaryTestingScore()
      if (result.data.code === 200) {
        // 等待一下让后端数据处理完成
        await new Promise(resolve => setTimeout(resolve, 1000))
        await fetchTestingPerformanceData()
        await fetchAllPerformanceAbstract()
        ElMessage.success(`${performanceItems.value.find(item => item.key === key)?.name}计算完成`)
      } else {
        ElMessage.error(result.data.msg || '计算失败')
      }
    } else if (key === 'wikiScore') {
      // WIKI得分绩效需要选择日期
      wikiScoreDate.value = ''
      wikiScoreDateVisible.value = true
      return
    } else if (key === 'maintenanceRecord') {
      // 维护记录数量绩效需要选择日期
      maintenanceScoreDate.value = ''
      maintenanceScoreDateVisible.value = true
      return
    } else if (key === 'onlineTestScore') {
      // 上线测试得分绩效需要选择日期
      onlineTestScoreDate.value = ''
      onlineTestScoreDateVisible.value = true
      return
    } else if (key === 'testCaseScore') {
      // 用例得分绩效需要选择日期
      useCaseScoreDate.value = ''
      useCaseScoreDateVisible.value = true
      return
    } else if (key === 'communication') {
      // 沟通协调得分绩效需要选择日期
      communicationScoreDate.value = ''
      communicationScoreDateVisible.value = true
      return
    } else if (key === 'poorDailyReport') {
      // 差的日报绩效需要选择日期
      poorDailyReportDate.value = ''
      poorDailyReportDateVisible.value = true
      return
    } else if (key === 'dailyReportRepetition') {
      // 日报重复率绩效需要选择日期
      dailyReportRepetitionDate.value = ''
      dailyReportRepetitionDateVisible.value = true
      return
    } else if (key === 'onlineOperation') {
      // 上线运维得分绩效需要选择日期
      onlineOperationScoreDate.value = ''
      onlineOperationScoreDateVisible.value = true
      return
    } else if (key === 'requirementScore') {
      const result = await summaryRequirementScore()
      if (result.data.code === 200) {
        // 等待一下让后端数据处理完成
        await new Promise(resolve => setTimeout(resolve, 1000))
        await fetchRequirementPerformanceData()
        await fetchAllPerformanceAbstract()
        ElMessage.success(`${performanceItems.value.find(item => item.key === key)?.name}计算完成`)
      } else {
        ElMessage.error(result.data.msg || '计算失败')
      }
    } else if (key === 'workloadScore') {
      // 工作量得分绩效需要选择日期
      workloadScoreDate.value = ''
      workloadScoreDateVisible.value = true
      return
    } else if (key === 'reportMaterial') {
      // 汇报材料得分绩效需要选择日期
      reportMaterialScoreDate.value = ''
      reportMaterialScoreDateVisible.value = true
      return
    } else if (key === 'businessTrip') {
      // 出差得分绩效需要选择日期
      businessTripScoreDate.value = ''
      businessTripScoreDateVisible.value = true
      return
    } else if (key === 'overtime') {
      const result = await summaryNetOvertimeHoursScore()
      if (result.data.code === 200) {
        await new Promise(resolve => setTimeout(resolve, 1000))
        await fetchNetOvertimePerformanceData()
        await fetchAllPerformanceAbstract()
        ElMessage.success(`${performanceItems.value.find(item => item.key === key)?.name}计算完成`)
      } else {
        ElMessage.error(result.data.msg || '计算失败')
      }
    } else if (key === 'faultDeduction') {
      // 故障评估扣分直接提示，无需计算
      ElMessage.info('故障评估扣分会在最终绩效中直接扣除，无需单独计算')
      return
    } else {
      // 其他绩效项目使用通用计算接口
      response = await calculatePerformanceAPI(key)
      if (response.success) {
        performanceData[key] = response.data
        // 刷新摘要信息
        await fetchAllPerformanceAbstract()
        ElMessage.success(`${performanceItems.value.find(item => item.key === key)?.name}计算完成`)
      } else {
        ElMessage.error(response.message || '计算失败')
      }
    }
  } catch (error) {
    ElMessage.error('计算失败')
  } finally {
    calculatingStates[key] = false
  }
}

// 重新计算（产品/分配任务/分配延期/研发任务/测试任务/WIKI得分/维护记录/上线测试得分/用例得分/沟通协调得分/上线运维得分/工作量得分）
const resetPerformance = async (key: string) => {
  if (!['product','assignedTask','assignedDelay','developmentDelay','developmentTask','testTask','wikiScore','maintenanceRecord','onlineTestScore','testCaseScore','communication','onlineOperation','requirementScore','workloadScore','reportMaterial','businessTrip','overtime','onlineRollback','inspectionMiss','onlineDelay','onlinePlanCompletion','onlineTaskCompletion','poorDailyReport','dailyReportRepetition'].includes(key)) return
  if (actionLoading[key]?.reset) return
  
  // WIKI得分绩效重新计算需要选择日期
  if (key === 'wikiScore') {
    actionLoading[key].reset = true
    wikiScoreDate.value = ''
    wikiScoreDateVisible.value = true
    return
  }
  // 上线运维及测试任务达成率 重新计算需要选择日期
  if (key === 'onlineTaskCompletion') {
    actionLoading[key].reset = true
    onlineTaskCompletionDate.value = ''
    onlineTaskCompletionDateVisible.value = true
    return
  }
  // 维护记录数量绩效重新计算需要选择日期
  if (key === 'maintenanceRecord') {
    actionLoading[key].reset = true
    maintenanceScoreDate.value = ''
    maintenanceScoreDateVisible.value = true
    return
  }
  // 上线测试得分绩效重新计算需要选择日期
  if (key === 'onlineTestScore') {
    actionLoading[key].reset = true
    onlineTestScoreDate.value = ''
    onlineTestScoreDateVisible.value = true
    return
  }
  // 用例得分绩效重新计算需要选择日期
  if (key === 'testCaseScore') {
    actionLoading[key].reset = true
    useCaseScoreDate.value = ''
    useCaseScoreDateVisible.value = true
    return
  }
  // 沟通协调得分绩效重新计算需要选择日期
  if (key === 'communication') {
    actionLoading[key].reset = true
    communicationScoreDate.value = ''
    communicationScoreDateVisible.value = true
    return
  }
  // 差的日报绩效重新计算需要选择日期
  if (key === 'poorDailyReport') {
    actionLoading[key].reset = true
    poorDailyReportDate.value = ''
    poorDailyReportDateVisible.value = true
    return
  }
  // 日报重复率绩效重新计算需要选择日期
  if (key === 'dailyReportRepetition') {
    actionLoading[key].reset = true
    dailyReportRepetitionDate.value = ''
    dailyReportRepetitionDateVisible.value = true
    return
  }
  // 上线运维得分绩效重新计算需要选择日期
  if (key === 'onlineOperation') {
    actionLoading[key].reset = true
    onlineOperationScoreDate.value = ''
    onlineOperationScoreDateVisible.value = true
    return
  }
  // 工作量得分绩效重新计算需要选择日期
  if (key === 'workloadScore') {
    actionLoading[key].reset = true
    workloadScoreDate.value = ''
    workloadScoreDateVisible.value = true
    return
  }
  // 汇报材料得分绩效重新计算需要选择日期
  if (key === 'reportMaterial') {
    actionLoading[key].reset = true
    reportMaterialScoreDate.value = ''
    reportMaterialScoreDateVisible.value = true
    return
  }
  // 上线延期数量绩效重新计算需要选择日期
  if (key === 'onlineDelay') {
    actionLoading[key].reset = true
    onlineDelayDate.value = ''
    onlineDelayDateVisible.value = true
    return
  }
  // 上线计划达成绩效重新计算需要选择日期
  if (key === 'onlinePlanCompletion') {
    actionLoading[key].reset = true
    onlinePlanCompletionDate.value = ''
    onlinePlanCompletionDateVisible.value = true
    return
  }
  // 上线回退次数绩效重新计算需要选择日期
  if (key === 'onlineRollback') {
    actionLoading[key].reset = true
    onlineRollbackDate.value = ''
    onlineRollbackDateVisible.value = true
    return
  }
  // 出差得分绩效重新计算需要选择日期
  if (key === 'businessTrip') {
    actionLoading[key].reset = true
    businessTripScoreDate.value = ''
    businessTripScoreDateVisible.value = true
    return
  }
  // 未巡检数量绩效重新计算需要选择日期
  if (key === 'inspectionMiss') {
    actionLoading[key].reset = true
    inspectionMissDate.value = ''
    inspectionMissDateVisible.value = true
    return
  }
  // 汇报材料得分绩效重新计算需要选择日期
  if (key === 'reportMaterial') {
    actionLoading[key].reset = true
    reportMaterialScoreDate.value = ''
    reportMaterialScoreDateVisible.value = true
    return
  }
  
  try {
    await ElMessageBox.confirm('重新计算将清空当前数据，是否继续？', '提示', {
      type: 'warning',
      confirmButtonText: '继续',
      cancelButtonText: '取消'
    })
  } catch (_) {
    return
  }
  actionLoading[key].reset = true
  try {
    const res = key === 'product' ? await GetResetSummaryPerformanceRequirement() : 
                (key === 'assignedTask' ? await resetSummaryAssignmentScore() : 
                (key === 'assignedDelay' ? await resetSummaryAssignmentDelayTasksScore() : 
                (key === 'developmentDelay' ? await resetSummaryDevelopmentDelayTasksScore() : 
                (key === 'developmentTask' ? await resetSummaryDevelopmentScore() : 
                (key === 'testTask' ? await resetSummaryTestingScore() : 
                (key === 'overtime' ? await resetSummaryNetOvertimeHoursScore() : 
                (key === 'requirementScore' ? await resetSummaryRequirementScore() : 
                (key === 'onlineRollback' ? await resetSummaryOnlineRollbackCountScore(onlineRollbackDate.value) : 
                (key === 'inspectionMiss' ? await resetSummaryItemUninspectedCountScore(inspectionMissDate.value) : 
                (key === 'onlineDelay' ? await resetSummaryItemOnlineDelayCount(onlineDelayDate.value) : 
                (key === 'onlinePlanCompletion' ? await resetSummaryItemOnlinePlanCompletionRate() : 
                (key === 'onlineTaskCompletion' ? await resetSummaryItemOnlineOperationTasks() : null))))))))))))
    if (res && res.data && res.data.code === 200) {
      if (key === 'product') await fetchProductPerformanceData()
      if (key === 'assignedTask') await fetchAssignedPerformanceData()
      if (key === 'assignedDelay') await fetchAssignedDelayPerformanceData()
      if (key === 'developmentTask') await fetchDevelopmentPerformanceData()
      if (key === 'developmentDelay') await fetchDevelopmentDelayPerformanceData()
      if (key === 'onlineRollback') await fetchOnlineRollbackPerformanceData()
      if (key === 'inspectionMiss') await fetchInspectionMissPerformanceData()
      if (key === 'testTask') await fetchTestingPerformanceData()
      if (key === 'requirementScore') await fetchRequirementPerformanceData()
      if (key === 'onlineDelay') await fetchOnlineDelayPerformanceData()
      if (key === 'onlinePlanCompletion') await fetchOnlinePlanCompletionPerformanceData()
      if (key === 'onlineTaskCompletion') await fetchOnlineTaskCompletionPerformanceData()
      await fetchAllPerformanceAbstract()
      ElMessage.success('重新计算完成')
    } else {
      ElMessage.error(res?.data?.msg || '重新计算失败')
    }
  } catch (e) {
    ElMessage.error('重新计算失败')
  } finally {
    actionLoading[key].reset = false
  }
}

// 存为历史数据（产品/分配任务/分配延期/研发任务/测试任务/WIKI得分/维护记录/上线测试得分/用例得分/沟通协调得分/上线运维得分/工作量得分）
const savePerformance = async (key: string) => {
  if (!['product','assignedTask','assignedDelay','developmentDelay','developmentTask','testTask','wikiScore','maintenanceRecord','onlineTestScore','testCaseScore','communication','onlineOperation','requirementScore','workloadScore','reportMaterial','businessTrip','overtime','onlineRollback','inspectionMiss','onlineDelay','onlinePlanCompletion','onlineTaskCompletion','poorDailyReport','dailyReportRepetition'].includes(key)) return
  if (actionLoading[key]?.save) return
  // 操作确认：提示存为历史数据的日期标签
  try {
    const now = new Date()
    const year = now.getFullYear()
    const month = String(now.getMonth() + 1).padStart(2, '0')
    const formattedMonth = `${year}年${month}月份`
    await ElMessageBox.confirm(`数据将作为${formattedMonth}绩效历史数据，是否继续？`, '提示', {
      type: 'warning',
      confirmButtonText: '继续',
      cancelButtonText: '取消'
    })
  } catch (_) {
    return
  }
  actionLoading[key].save = true
  try {
    let res
    if (key === 'product') {
      res = await GetSaveSummaryPerformanceRequirement()
    } else if (key === 'assignedTask') {
      res = await saveSummaryAssignmentScore()
    } else if (key === 'assignedDelay') {
      res = await saveSummaryAssignmentDelayTasksScore()
    } else if (key === 'developmentDelay') {
      res = await saveSummaryDevelopmentDelayTasksScore()
    } else if (key === 'onlineDelay') {
      res = await saveSummaryItemOnlineDelayCount()
    } else if (key === 'onlinePlanCompletion') {
      res = await saveSummaryItemOnlinePlanCompletionRate()
    } else if (key === 'onlineTaskCompletion') {
      res = await saveSummaryItemOnlineOperationTasks()
    } else if (key === 'developmentTask') {
      res = await saveSummaryDevelopmentScore()
    } else if (key === 'testTask') {
      res = await saveSummaryTestingScore()
    } else if (key === 'wikiScore') {
      res = await saveSummaryWikiScore()
    } else if (key === 'maintenanceRecord') {
      res = await saveSummaryMaintenanceScore()
    } else if (key === 'onlineTestScore') {
      res = await saveSummaryOnlineTestingScore()
    } else if (key === 'testCaseScore') {
      res = await saveSummaryUseCaseScore()
    } else if (key === 'communication') {
      res = await saveSummaryCommunicationScore()
    } else if (key === 'poorDailyReport') {
      res = await saveSummaryItemPoorDailyReports()
    } else if (key === 'dailyReportRepetition') {
      res = await saveSummaryItemDailyReportRepetitionRate()
    } else if (key === 'onlineOperation') {
      res = await saveSummaryOnlineOperationScore()
    } else if (key === 'workloadScore') {
      res = await saveSummaryWorkloadScore()
    } else if (key === 'reportMaterial') {
      res = await saveSummaryReportMaterialScore()
    } else if (key === 'businessTrip') {
      res = await saveSummaryBusinessTripScore()
    } else if (key === 'overtime') {
      res = await saveSummaryNetOvertimeHoursScore()
    } else if (key === 'onlineRollback') {
      res = await saveSummaryOnlineRollbackCountScore()
    } else if (key === 'inspectionMiss') {
      res = await saveSummaryItemUninspectedCountScore()
    } else {
      res = await saveSummaryRequirementScore()
    }
    if (res && res.data && res.data.code === 200) {
      // 存为历史数据后，刷新摘要与数据以同步状态
      if (key === 'product') await fetchProductPerformanceData()
      if (key === 'assignedTask') await fetchAssignedPerformanceData()
      if (key === 'assignedDelay') await fetchAssignedDelayPerformanceData()
      if (key === 'developmentDelay') await fetchDevelopmentDelayPerformanceData()
      if (key === 'developmentTask') await fetchDevelopmentPerformanceData()
      if (key === 'testTask') await fetchTestingPerformanceData()
      if (key === 'onlineRollback') await fetchOnlineRollbackPerformanceData()
      if (key === 'inspectionMiss') await fetchInspectionMissPerformanceData()
      if (key === 'wikiScore') await fetchWikiPerformanceData()
      if (key === 'maintenanceRecord') await fetchMaintenancePerformanceData()
      if (key === 'onlineTestScore') await fetchOnlineTestPerformanceData()
      if (key === 'testCaseScore') await fetchUseCasePerformanceData()
      if (key === 'communication') await fetchCommunicationPerformanceData()
      if (key === 'onlineOperation') await fetchOnlineOperationPerformanceData()
      if (key === 'requirementScore') await fetchRequirementPerformanceData()
      if (key === 'overtime') await fetchNetOvertimePerformanceData()
      if (key === 'workloadScore') await fetchWorkloadPerformanceData()
      if (key === 'reportMaterial') await fetchReportMaterialPerformanceData()
      if (key === 'businessTrip') await fetchBusinessTripPerformanceData()
      if (key === 'onlineDelay') await fetchOnlineDelayPerformanceData()
      if (key === 'onlinePlanCompletion') await fetchOnlinePlanCompletionPerformanceData()
      if (key === 'onlineTaskCompletion') await fetchOnlineTaskCompletionPerformanceData()
      await fetchAllPerformanceAbstract()
      ElMessage.success('已存为历史数据')
    } else {
      ElMessage.error(res.data?.msg || '存为历史数据失败')
    }
  } catch (e) {
    ElMessage.error('存为历史数据失败')
  } finally {
    actionLoading[key].save = false
  }
}

// 获取产品绩效数据
const fetchProductPerformanceData = async () => {
  detailsLoading.value = true
  try {
    const result = await GetGetSummaryPerformanceRequirement()
    if (result.data && result.data.code === 200) {
      const list = Array.isArray(result.data.data) ? result.data.data : []
      if (list.length > 0) {
        const normalizedList = list.map((it: any) => ({
          ...it,
          userName: it.userName ?? it.versionUserName,
          score: it.score ?? it.rankNumber,
          scoreRank: it.scoreRank ?? it.rankRanking
        }))
        const firstItem = normalizedList[0]
        const standardData = {
          recentDate: firstItem.versionDate,
          position: firstItem.versionPost,
          employeeName: firstItem.versionUserName,
          positionCoefficient: firstItem.jobXs,
          baseCoefficient: firstItem.jobXsjc,
          basePerformance: firstItem.basePerformance,
          scoreRank: firstItem.rankRanking,
          performanceScore: firstItem.rankScore,
          score: firstItem.rankNumber,
          performanceType: firstItem.levelType,
          rawData: normalizedList
        }
        performanceData['product'] = standardData
      } else {
        // 清空现有数据，避免打开空弹窗
        delete performanceData['product']
        await fetchAllPerformanceAbstract()
      }
    } else {
      ElMessage.error('获取产品绩效数据失败')
    }
  } catch (error) {
    ElMessage.error('获取产品绩效数据失败')
  }
  detailsLoading.value = false
}

// 获取需求得分绩效数据（与分配任务绩效相同结构）
const fetchRequirementPerformanceData = async () => {
  detailsLoading.value = true
  try {
    const result = await getSummaryRequirementScore()
    if (result.data && result.data.code === 200) {
      const list = Array.isArray(result.data.data) ? result.data.data : []
      if (list.length > 0) {
        const normalizedList = list.map((it: any) => ({
          ...it,
          userName: it.userName ?? it.versionUserName,
          score: it.score ?? it.rankNumber,
          scoreRank: it.scoreRank ?? it.rankRanking
        }))
        const firstItem = normalizedList[0]
        const standardData = {
          recentDate: firstItem.versionDate,
          position: firstItem.versionPost,
          employeeName: firstItem.versionUserName,
          positionCoefficient: firstItem.jobXs,
          baseCoefficient: firstItem.jobXsjc,
          basePerformance: firstItem.basePerformance,
          scoreRank: firstItem.rankRanking,
          performanceScore: firstItem.rankScore,
          score: firstItem.rankNumber,
          performanceType: firstItem.levelType,
          rawData: normalizedList
        }
        performanceData['requirementScore'] = standardData
      } else {
        delete performanceData['requirementScore']
        await fetchAllPerformanceAbstract()
      }
    } else {
      ElMessage.error('获取需求得分绩效数据失败')
    }
  } catch (error) {
    ElMessage.error('获取需求得分绩效数据失败')
  }
  detailsLoading.value = false
}

// 获取上线测试得分绩效数据
const fetchOnlineTestPerformanceData = async () => {
  detailsLoading.value = true
  try {
    const result = await getSummaryOnlineTestingScore()
    if (result.data && result.data.code === 200) {
      const list = Array.isArray(result.data.data) ? result.data.data : []
      if (list.length > 0) {
        const normalizedList = list.map((it: any) => ({
          ...it,
          userName: it.userName ?? it.versionUserName,
          score: it.score ?? it.rankNumber,
          scoreRank: it.scoreRank ?? it.rankRanking
        }))
        const firstItem = normalizedList[0]
        const standardData = {
          recentDate: firstItem.versionDate,
          position: firstItem.versionPost,
          employeeName: firstItem.versionUserName,
          positionCoefficient: firstItem.jobXs,
          baseCoefficient: firstItem.jobXsjc,
          basePerformance: firstItem.basePerformance,
          scoreRank: firstItem.rankRanking,
          performanceScore: firstItem.rankScore,
          score: firstItem.rankNumber,
          performanceType: firstItem.levelType,
          rawData: normalizedList
        }
        performanceData['onlineTestScore'] = standardData
      } else {
        delete performanceData['onlineTestScore']
        await fetchAllPerformanceAbstract()
      }
    } else {
      ElMessage.error('获取上线测试得分绩效数据失败')
    }
  } catch (error) {
    ElMessage.error('获取上线测试得分绩效数据失败')
  }
  detailsLoading.value = false
}

// 获取用例得分绩效数据
const fetchUseCasePerformanceData = async () => {
  detailsLoading.value = true
  try {
    const result = await getSummaryUseCaseScore()
    if (result.data && result.data.code === 200) {
      const list = Array.isArray(result.data.data) ? result.data.data : []
      if (list.length > 0) {
        const normalizedList = list.map((it: any) => ({
          ...it,
          userName: it.userName ?? it.versionUserName,
          score: it.score ?? it.rankNumber,
          scoreRank: it.scoreRank ?? it.rankRanking
        }))
        const firstItem = normalizedList[0]
        const standardData = {
          recentDate: firstItem.versionDate,
          position: firstItem.versionPost,
          employeeName: firstItem.versionUserName,
          positionCoefficient: firstItem.jobXs,
          baseCoefficient: firstItem.jobXsjc,
          basePerformance: firstItem.basePerformance,
          scoreRank: firstItem.rankRanking,
          performanceScore: firstItem.rankScore,
          score: firstItem.rankNumber,
          performanceType: firstItem.levelType,
          rawData: normalizedList
        }
        performanceData['testCaseScore'] = standardData
      } else {
        delete performanceData['testCaseScore']
        await fetchAllPerformanceAbstract()
      }
    } else {
      ElMessage.error('获取用例得分绩效数据失败')
    }
  } catch (error) {
    ElMessage.error('获取用例得分绩效数据失败')
  }
  detailsLoading.value = false
}

// 获取沟通协调得分绩效数据
const fetchCommunicationPerformanceData = async () => {
  detailsLoading.value = true
  try {
    const result = await getSummaryCommunicationScore()
    if (result.data && result.data.code === 200) {
      const list = Array.isArray(result.data.data) ? result.data.data : []
      if (list.length > 0) {
        const normalizedList = list.map((it: any) => ({
          ...it,
          userName: it.userName ?? it.versionUserName,
          score: it.score ?? it.rankNumber,
          scoreRank: it.scoreRank ?? it.rankRanking
        }))
        const firstItem = normalizedList[0]
        const standardData = {
          recentDate: firstItem.versionDate,
          position: firstItem.versionPost,
          employeeName: firstItem.versionUserName,
          positionCoefficient: firstItem.jobXs,
          baseCoefficient: firstItem.jobXsjc,
          basePerformance: firstItem.basePerformance,
          scoreRank: firstItem.rankRanking,
          performanceScore: firstItem.rankScore,
          score: firstItem.rankNumber,
          performanceType: firstItem.levelType,
          rawData: normalizedList
        }
        performanceData['communication'] = standardData
      } else {
        delete performanceData['communication']
        await fetchAllPerformanceAbstract()
      }
    } else {
      ElMessage.error('获取沟通协调得分绩效数据失败')
    }
  } catch (error) {
    ElMessage.error('获取沟通协调得分绩效数据失败')
  }
  detailsLoading.value = false
}

// 获取差的日报绩效数据
const fetchPoorDailyReportPerformanceData = async () => {
  detailsLoading.value = true
  try {
    const result = await getSummaryItemPoorDailyReports()
    if (result.data && result.data.code === 200) {
      const list = Array.isArray(result.data.data) ? result.data.data : []
      if (list.length > 0) {
        const normalizedList = list.map((it: any) => ({
          ...it,
          userName: it.userName ?? it.versionUserName,
          score: it.score ?? it.rankNumber,
          scoreRank: it.scoreRank ?? it.rankRanking
        }))
        const firstItem = normalizedList[0]
        const standardData = {
          recentDate: firstItem.versionDate,
          position: firstItem.versionPost,
          employeeName: firstItem.versionUserName,
          positionCoefficient: firstItem.jobXs,
          baseCoefficient: firstItem.jobXsjc,
          basePerformance: firstItem.basePerformance,
          scoreRank: firstItem.rankRanking,
          performanceScore: firstItem.rankScore,
          score: firstItem.rankNumber,
          performanceType: firstItem.levelType,
          rawData: normalizedList
        }
        performanceData['poorDailyReport'] = standardData
      } else {
        delete performanceData['poorDailyReport']
        await fetchAllPerformanceAbstract()
      }
    } else {
      ElMessage.error('获取差的日报绩效数据失败')
    }
  } catch (error) {
    ElMessage.error('获取差的日报绩效数据失败')
  }
  detailsLoading.value = false
}

// 获取日报重复率绩效数据
const fetchDailyReportRepetitionPerformanceData = async () => {
  detailsLoading.value = true
  try {
    const result = await getSummaryItemDailyReportRepetitionRate()
    if (result.data && result.data.code === 200) {
      const list = Array.isArray(result.data.data) ? result.data.data : []
      if (list.length > 0) {
        const normalizedList = list.map((it: any) => ({
          ...it,
          userName: it.userName ?? it.versionUserName,
          score: it.score ?? it.rankNumber,
          scoreRank: it.scoreRank ?? it.rankRanking
        }))
        const firstItem = normalizedList[0]
        const standardData = {
          recentDate: firstItem.versionDate,
          position: firstItem.versionPost,
          employeeName: firstItem.versionUserName,
          positionCoefficient: firstItem.jobXs,
          baseCoefficient: firstItem.jobXsjc,
          basePerformance: firstItem.basePerformance,
          scoreRank: firstItem.rankRanking,
          performanceScore: firstItem.rankScore,
          score: firstItem.rankNumber,
          performanceType: firstItem.levelType,
          rawData: normalizedList
        }
        performanceData['dailyReportRepetition'] = standardData
      } else {
        delete performanceData['dailyReportRepetition']
        await fetchAllPerformanceAbstract()
      }
    } else {
      ElMessage.error('获取日报重复率绩效数据失败')
    }
  } catch (error) {
    ElMessage.error('获取日报重复率绩效数据失败')
  }
  detailsLoading.value = false
}

// 获取上线运维得分绩效数据
const fetchOnlineOperationPerformanceData = async () => {
  detailsLoading.value = true
  try {
    const result = await getSummaryOnlineOperationScore()
    if (result.data && result.data.code === 200) {
      const list = Array.isArray(result.data.data) ? result.data.data : []
      if (list.length > 0) {
        const normalizedList = list.map((it: any) => ({
          ...it,
          userName: it.userName ?? it.versionUserName,
          score: it.score ?? it.rankNumber,
          scoreRank: it.scoreRank ?? it.rankRanking
        }))
        const firstItem = normalizedList[0]
        const standardData = {
          recentDate: firstItem.versionDate,
          position: firstItem.versionPost,
          employeeName: firstItem.versionUserName,
          positionCoefficient: firstItem.jobXs,
          baseCoefficient: firstItem.jobXsjc,
          basePerformance: firstItem.basePerformance,
          scoreRank: firstItem.rankRanking,
          performanceScore: firstItem.rankScore,
          score: firstItem.rankNumber,
          performanceType: firstItem.levelType,
          rawData: normalizedList
        }
        performanceData['onlineOperation'] = standardData
      } else {
        delete performanceData['onlineOperation']
        await fetchAllPerformanceAbstract()
      }
    } else {
      ElMessage.error('获取上线运维得分绩效数据失败')
    }
  } catch (error) {
    ElMessage.error('获取上线运维得分绩效数据失败')
  }
  detailsLoading.value = false
}

// 获取分配任务绩效数据
const fetchAssignedPerformanceData = async () => {
  detailsLoading.value = true
  try {
    const result = await getSummaryAssignmentScore()
    if (result.data && result.data.code === 200) {
      const list = Array.isArray(result.data.data) ? result.data.data : []
      if (list.length > 0) {
        const normalizedList = list.map((it: any) => ({
          ...it,
          userName: it.userName ?? it.versionUserName,
          score: it.score ?? it.rankNumber,
          scoreRank: it.scoreRank ?? it.rankRanking
        }))
        const firstItem = normalizedList[0]
        const standardData = {
          recentDate: firstItem.versionDate,
          position: firstItem.versionPost,
          employeeName: firstItem.versionUserName,
          positionCoefficient: firstItem.jobXs,
          baseCoefficient: firstItem.jobXsjc,
          basePerformance: firstItem.basePerformance,
          scoreRank: firstItem.rankRanking,
          performanceScore: firstItem.rankScore,
          score: firstItem.rankNumber,
          performanceType: firstItem.levelType,
          rawData: normalizedList
        }
        performanceData['assignedTask'] = standardData
      } else {
        delete performanceData['assignedTask']
        await fetchAllPerformanceAbstract()
      }
    } else {
      ElMessage.error('获取分配任务绩效数据失败')
    }
  } catch (error) {
    ElMessage.error('获取分配任务绩效数据失败')
  }
  detailsLoading.value = false
}

// 获取分配延期绩效数据
const fetchAssignedDelayPerformanceData = async () => {
  detailsLoading.value = true
  try {
    const result = await getSummaryAssignmentDelayTasksScore()
    if (result.data && result.data.code === 200) {
      const list = Array.isArray(result.data.data) ? result.data.data : []
      if (list.length > 0) {
        const normalizedList = list.map((it: any) => ({
          ...it,
          userName: it.userName ?? it.versionUserName,
          score: it.score ?? it.rankNumber,
          scoreRank: it.scoreRank ?? it.rankRanking
        }))
        const firstItem = normalizedList[0]
        const standardData = {
          recentDate: firstItem.versionDate,
          position: firstItem.versionPost,
          employeeName: firstItem.versionUserName,
          positionCoefficient: firstItem.jobXs,
          baseCoefficient: firstItem.jobXsjc,
          basePerformance: firstItem.basePerformance,
          scoreRank: firstItem.rankRanking,
          performanceScore: firstItem.rankScore,
          score: firstItem.rankNumber,
          performanceType: firstItem.levelType,
          rawData: normalizedList
        }
        performanceData['assignedDelay'] = standardData
      } else {
        delete performanceData['assignedDelay']
        await fetchAllPerformanceAbstract()
      }
    } else {
      ElMessage.error('获取分配延期绩效数据失败')
    }
  } catch (error) {
    ElMessage.error('获取分配延期绩效数据失败')
  }
  detailsLoading.value = false
}

// 获取研发延期任务绩效数据
const fetchDevelopmentDelayPerformanceData = async () => {
  detailsLoading.value = true
  try {
    const result = await getSummaryDevelopmentDelayTasksScore()
    if (result.data && result.data.code === 200) {
      const list = Array.isArray(result.data.data) ? result.data.data : []
      if (list.length > 0) {
        const normalizedList = list.map((it: any) => ({
          ...it,
          userName: it.userName ?? it.versionUserName,
          score: it.score ?? it.rankNumber,
          scoreRank: it.scoreRank ?? it.rankRanking
        }))
        const firstItem = normalizedList[0]
        const standardData = {
          recentDate: firstItem.versionDate,
          position: firstItem.versionPost,
          employeeName: firstItem.versionUserName,
          positionCoefficient: firstItem.jobXs,
          baseCoefficient: firstItem.jobXsjc,
          basePerformance: firstItem.basePerformance,
          scoreRank: firstItem.rankRanking,
          performanceScore: firstItem.rankScore,
          score: firstItem.rankNumber,
          performanceType: firstItem.levelType,
          rawData: normalizedList
        }
        performanceData['developmentDelay'] = standardData
      } else {
        delete performanceData['developmentDelay']
        await fetchAllPerformanceAbstract()
      }
    } else {
      ElMessage.error('获取研发延期任务绩效数据失败')
    }
  } catch (error) {
    ElMessage.error('获取研发延期任务绩效数据失败')
  }
  detailsLoading.value = false
}

// 获取维护记录数量绩效数据
const fetchMaintenancePerformanceData = async () => {
  detailsLoading.value = true
  try {
    const result = await getSummaryMaintenanceScore()
    if (result.data && result.data.code === 200) {
      const list = Array.isArray(result.data.data) ? result.data.data : []
      if (list.length > 0) {
        const normalizedList = list.map((it: any) => ({
          ...it,
          userName: it.userName ?? it.versionUserName,
          score: it.score ?? it.rankNumber,
          scoreRank: it.scoreRank ?? it.rankRanking
        }))
        const firstItem = normalizedList[0]
        const standardData = {
          recentDate: firstItem.versionDate,
          position: firstItem.versionPost,
          employeeName: firstItem.versionUserName,
          positionCoefficient: firstItem.jobXs,
          baseCoefficient: firstItem.jobXsjc,
          basePerformance: firstItem.basePerformance,
          scoreRank: firstItem.rankRanking,
          performanceScore: firstItem.rankScore,
          score: firstItem.rankNumber,
          performanceType: firstItem.levelType,
          rawData: normalizedList
        }
        performanceData['maintenanceRecord'] = standardData
      } else {
        delete performanceData['maintenanceRecord']
        await fetchAllPerformanceAbstract()
      }
    } else {
      ElMessage.error('获取维护记录数量绩效数据失败')
    }
  } catch (error) {
    ElMessage.error('获取维护记录数量绩效数据失败')
  }
  detailsLoading.value = false
}

// 获取研发任务绩效数据
const fetchDevelopmentPerformanceData = async () => {
  detailsLoading.value = true
  try {
    const result = await getSummaryDevelopmentScore()
    if (result.data && result.data.code === 200) {
      const list = Array.isArray(result.data.data) ? result.data.data : []
      if (list.length > 0) {
        const normalizedList = list.map((it: any) => ({
          ...it,
          userName: it.userName ?? it.versionUserName,
          score: it.score ?? it.rankNumber,
          scoreRank: it.scoreRank ?? it.rankRanking
        }))
        const firstItem = normalizedList[0]
        const standardData = {
          recentDate: firstItem.versionDate,
          position: firstItem.versionPost,
          employeeName: firstItem.versionUserName,
          positionCoefficient: firstItem.jobXs,
          baseCoefficient: firstItem.jobXsjc,
          basePerformance: firstItem.basePerformance,
          scoreRank: firstItem.rankRanking,
          performanceScore: firstItem.rankScore,
          score: firstItem.rankNumber,
          performanceType: firstItem.levelType,
          rawData: normalizedList
        }
        performanceData['developmentTask'] = standardData
      } else {
        delete performanceData['developmentTask']
        await fetchAllPerformanceAbstract()
      }
    } else {
      ElMessage.error('获取研发任务绩效数据失败')
    }
  } catch (error) {
    ElMessage.error('获取研发任务绩效数据失败')
  }
  detailsLoading.value = false
}

// 获取测试任务绩效数据
const fetchTestingPerformanceData = async () => {
  detailsLoading.value = true
  try {
    const result = await getSummaryTestingScore()
    if (result.data && result.data.code === 200) {
      const list = Array.isArray(result.data.data) ? result.data.data : []
      if (list.length > 0) {
        const normalizedList = list.map((it: any) => ({
          ...it,
          userName: it.userName ?? it.versionUserName,
          score: it.score ?? it.rankNumber,
          scoreRank: it.scoreRank ?? it.rankRanking
        }))
        const firstItem = normalizedList[0]
        const standardData = {
          recentDate: firstItem.versionDate,
          position: firstItem.versionPost,
          employeeName: firstItem.versionUserName,
          positionCoefficient: firstItem.jobXs,
          baseCoefficient: firstItem.jobXsjc,
          basePerformance: firstItem.basePerformance,
          scoreRank: firstItem.rankRanking,
          performanceScore: firstItem.rankScore,
          score: firstItem.rankNumber,
          performanceType: firstItem.levelType,
          rawData: normalizedList
        }
        performanceData['testTask'] = standardData
      } else {
        delete performanceData['testTask']
        await fetchAllPerformanceAbstract()
      }
    } else {
      ElMessage.error('获取测试任务绩效数据失败')
    }
  } catch (error) {
    ElMessage.error('获取测试任务绩效数据失败')
  }
  detailsLoading.value = false
}

// 获取WIKI得分绩效数据
const fetchWikiPerformanceData = async () => {
  detailsLoading.value = true
  try {
    const result = await getSummaryWikiScore()
    if (result.data && result.data.code === 200) {
      const list = Array.isArray(result.data.data) ? result.data.data : []
      if (list.length > 0) {
        const normalizedList = list.map((it: any) => ({
          ...it,
          userName: it.userName ?? it.versionUserName,
          score: it.score ?? it.rankNumber,
          scoreRank: it.scoreRank ?? it.rankRanking
        }))
        const firstItem = normalizedList[0]
        const standardData = {
          recentDate: firstItem.versionDate,
          position: firstItem.versionPost,
          employeeName: firstItem.versionUserName,
          positionCoefficient: firstItem.jobXs,
          baseCoefficient: firstItem.jobXsjc,
          basePerformance: firstItem.basePerformance,
          scoreRank: firstItem.rankRanking,
          performanceScore: firstItem.rankScore,
          score: firstItem.rankNumber,
          performanceType: firstItem.levelType,
          rawData: normalizedList
        }
        performanceData['wikiScore'] = standardData
      } else {
        delete performanceData['wikiScore']
        await fetchAllPerformanceAbstract()
      }
    } else {
      ElMessage.error('获取WIKI得分绩效数据失败')
    }
  } catch (error) {
    ElMessage.error('获取WIKI得分绩效数据失败')
  }
  detailsLoading.value = false
}

// 获取净加班绩效数据（结构与测试任务类似）
const fetchNetOvertimePerformanceData = async () => {
  detailsLoading.value = true
  try {
    const result = await getSummaryNetOvertimeHoursScore()
    if (result.data && result.data.code === 200) {
      const list = Array.isArray(result.data.data) ? result.data.data : []
      if (list.length > 0) {
        const normalizedList = list.map((it: any) => ({
          ...it,
          userName: it.userName ?? it.versionUserName,
          score: it.score ?? it.rankNumber,
          scoreRank: it.scoreRank ?? it.rankRanking
        }))
        const firstItem = normalizedList[0]
        const standardData = {
          recentDate: firstItem.versionDate,
          position: firstItem.versionPost,
          employeeName: firstItem.versionUserName,
          positionCoefficient: firstItem.jobXs,
          baseCoefficient: firstItem.jobXsjc,
          basePerformance: firstItem.basePerformance,
          scoreRank: firstItem.rankRanking,
          performanceScore: firstItem.rankScore,
          score: firstItem.rankNumber,
          performanceType: firstItem.levelType,
          rawData: normalizedList
        }
        performanceData['overtime'] = standardData
      } else {
        delete performanceData['overtime']
        await fetchAllPerformanceAbstract()
      }
    } else {
      ElMessage.error('获取净加班绩效数据失败')
    }
  } catch (error) {
    ElMessage.error('获取净加班绩效数据失败')
  }
  detailsLoading.value = false
}

// 获取上线回退次数绩效数据（结构与研发延期任务绩效一致）
const fetchOnlineRollbackPerformanceData = async () => {
  detailsLoading.value = true
  try {
    const result = await getSummaryOnlineRollbackCountScore()
    if (result.data && result.data.code === 200) {
      const list = Array.isArray(result.data.data) ? result.data.data : []
      if (list.length > 0) {
        const normalizedList = list.map((it: any) => ({
          ...it,
          userName: it.userName ?? it.versionUserName,
          score: it.score ?? it.rankNumber,
          scoreRank: it.scoreRank ?? it.rankRanking
        }))
        const firstItem = normalizedList[0]
        const standardData = {
          recentDate: firstItem.versionDate,
          position: firstItem.versionPost,
          employeeName: firstItem.versionUserName,
          positionCoefficient: firstItem.jobXs,
          baseCoefficient: firstItem.jobXsjc,
          basePerformance: firstItem.basePerformance,
          scoreRank: firstItem.rankRanking,
          performanceScore: firstItem.rankScore,
          score: firstItem.rankNumber,
          performanceType: firstItem.levelType,
          rawData: normalizedList
        }
        performanceData['onlineRollback'] = standardData
      } else {
        delete performanceData['onlineRollback']
        await fetchAllPerformanceAbstract()
      }
    } else {
      ElMessage.error('获取上线回退次数绩效数据失败')
    }
  } catch (error) {
    ElMessage.error('获取上线回退次数绩效数据失败')
  }
  detailsLoading.value = false
}

// 获取未巡检数量绩效数据（结构与研发延期任务绩效一致）
const fetchInspectionMissPerformanceData = async () => {
  detailsLoading.value = true
  try {
    const result = await getSummaryItemUninspectedCountScore()
    if (result.data && result.data.code === 200) {
      const list = Array.isArray(result.data.data) ? result.data.data : []
      if (list.length > 0) {
        const normalizedList = list.map((it: any) => ({
          ...it,
          userName: it.userName ?? it.versionUserName,
          score: it.score ?? it.rankNumber,
          scoreRank: it.scoreRank ?? it.rankRanking
        }))
        const firstItem = normalizedList[0]
        const standardData = {
          recentDate: firstItem.versionDate,
          position: firstItem.versionPost,
          employeeName: firstItem.versionUserName,
          positionCoefficient: firstItem.jobXs,
          baseCoefficient: firstItem.jobXsjc,
          basePerformance: firstItem.basePerformance,
          scoreRank: firstItem.rankRanking,
          performanceScore: firstItem.rankScore,
          score: firstItem.rankNumber,
          performanceType: firstItem.levelType,
          rawData: normalizedList
        }
        performanceData['inspectionMiss'] = standardData
      } else {
        delete performanceData['inspectionMiss']
        await fetchAllPerformanceAbstract()
      }
    } else {
      ElMessage.error('获取未巡检数量绩效数据失败')
    }
  } catch (error) {
    ElMessage.error('获取未巡检数量绩效数据失败')
  }
  detailsLoading.value = false
}

// 获取上线延期数量绩效数据（结构与研发延期任务绩效一致）
const fetchOnlineDelayPerformanceData = async () => {
  detailsLoading.value = true
  try {
    const result = await getSummaryItemOnlineDelayCount()
    if (result.data && result.data.code === 200) {
      const list = Array.isArray(result.data.data) ? result.data.data : []
      if (list.length > 0) {
        const normalizedList = list.map((it: any) => ({
          ...it,
          userName: it.userName ?? it.versionUserName,
          score: it.score ?? it.rankNumber,
          scoreRank: it.scoreRank ?? it.rankRanking
        }))
        const firstItem = normalizedList[0]
        const standardData = {
          recentDate: firstItem.versionDate,
          position: firstItem.versionPost,
          employeeName: firstItem.versionUserName,
          positionCoefficient: firstItem.jobXs,
          baseCoefficient: firstItem.jobXsjc,
          basePerformance: firstItem.basePerformance,
          scoreRank: firstItem.rankRanking,
          performanceScore: firstItem.rankScore,
          score: firstItem.rankNumber,
          performanceType: firstItem.levelType,
          rawData: normalizedList
        }
        performanceData['onlineDelay'] = standardData
      } else {
        delete performanceData['onlineDelay']
        await fetchAllPerformanceAbstract()
      }
    } else {
      ElMessage.error('获取上线延期数量绩效数据失败')
    }
  } catch (error) {
    ElMessage.error('获取上线延期数量绩效数据失败')
  }
  detailsLoading.value = false
}

// 获取上线计划达成绩效数据（结构与研发延期任务绩效一致）
const fetchOnlinePlanCompletionPerformanceData = async () => {
  detailsLoading.value = true
  try {
    const result = await getSummaryItemOnlinePlanCompletionRate()
    if (result.data && result.data.code === 200) {
      const list = Array.isArray(result.data.data) ? result.data.data : []
      if (list.length > 0) {
        const normalizedList = list.map((it: any) => ({
          ...it,
          userName: it.userName ?? it.versionUserName,
          score: it.score ?? it.rankNumber,
          scoreRank: it.scoreRank ?? it.rankRanking
        }))
        const firstItem = normalizedList[0]
        const standardData = {
          recentDate: firstItem.versionDate,
          position: firstItem.versionPost,
          employeeName: firstItem.versionUserName,
          positionCoefficient: firstItem.jobXs,
          baseCoefficient: firstItem.jobXsjc,
          basePerformance: firstItem.basePerformance,
          scoreRank: firstItem.rankRanking,
          performanceScore: firstItem.rankScore,
          score: firstItem.rankNumber,
          performanceType: firstItem.levelType,
          rawData: normalizedList
        }
        performanceData['onlinePlanCompletion'] = standardData
      } else {
        delete performanceData['onlinePlanCompletion']
        await fetchAllPerformanceAbstract()
      }
    } else {
      ElMessage.error('获取上线计划达成绩效数据失败')
    }
  } catch (error) {
    ElMessage.error('获取上线计划达成绩效数据失败')
  }
  detailsLoading.value = false
}

// 获取上线运维及测试任务达成率绩效数据（结构与上线计划达成绩效一致）
const fetchOnlineTaskCompletionPerformanceData = async () => {
  detailsLoading.value = true
  try {
    const result = await getSummaryItemOnlineOperationTasks()
    if (result.data && result.data.code === 200) {
      const list = Array.isArray(result.data.data) ? result.data.data : []
      if (list.length > 0) {
        const normalizedList = list.map((it: any) => ({
          ...it,
          userName: it.userName ?? it.versionUserName,
          score: it.score ?? it.rankNumber,
          scoreRank: it.scoreRank ?? it.rankRanking
        }))
        const firstItem = normalizedList[0]
        const standardData = {
          recentDate: firstItem.versionDate,
          position: firstItem.versionPost,
          employeeName: firstItem.versionUserName,
          positionCoefficient: firstItem.jobXs,
          baseCoefficient: firstItem.jobXsjc,
          basePerformance: firstItem.basePerformance,
          scoreRank: firstItem.rankRanking,
          performanceScore: firstItem.rankScore,
          score: firstItem.rankNumber,
          performanceType: firstItem.levelType,
          rawData: normalizedList
        }
        performanceData['onlineTaskCompletion'] = standardData
      } else {
        delete performanceData['onlineTaskCompletion']
        await fetchAllPerformanceAbstract()
      }
    } else {
      ElMessage.error('获取上线运维及测试任务达成率绩效数据失败')
    }
  } catch (error) {
    ElMessage.error('获取上线运维及测试任务达成率绩效数据失败')
  }
  detailsLoading.value = false
}

// 显示详细数据
const showDetails = () => {
  detailsVisible.value = true
}

// 表格行样式：高亮前3名
const rowClassName = ({ row }: { row: any }) => {
  const rank = row?.scoreRank
  if (rank === 1) return 'row-rank-top1'
  if (rank === 2) return 'row-rank-top2'
  if (rank === 3) return 'row-rank-top3'
  return ''
}

// 排名标签类型
const getRankTagType = (rank?: number) => {
  if (rank === 1) return 'danger'
  if (rank === 2) return 'warning'
  if (rank === 3) return 'success'
  return 'info'
}

// 导出详细数据
const exportPerformanceData = () => {
  const key = currentDetailType.value
  if (performanceData[key] && performanceData[key].rawData) {
    const dataStr = JSON.stringify(performanceData[key].rawData, null, 2)
    const dataBlob = new Blob([dataStr], { type: 'application/json' })
    const url = URL.createObjectURL(dataBlob)
    const link = document.createElement('a')
    link.href = url
    link.download = `${key}-performance-data-${new Date().toISOString().split('T')[0]}.json`
    link.click()
    URL.revokeObjectURL(url)
    ElMessage.success('数据导出成功')
  }
}

// 处理维护记录数量绩效日期选择取消
const handleMaintenanceScoreDateCancel = () => {
  maintenanceScoreDateVisible.value = false
  // 重置加载状态
  calculatingStates['maintenanceRecord'] = false
  if (actionLoading['maintenanceRecord']?.reset) {
    actionLoading['maintenanceRecord'].reset = false
  }
}

// 处理维护记录数量绩效日期选择对话框关闭
const handleMaintenanceScoreDateClose = () => {
  // 重置加载状态
  calculatingStates['maintenanceRecord'] = false
  if (actionLoading['maintenanceRecord']?.reset) {
    actionLoading['maintenanceRecord'].reset = false
  }
}

// 确认维护记录数量绩效日期选择
const confirmMaintenanceScoreDate = async () => {
  if (!maintenanceScoreDate.value) {
    ElMessage.warning('请选择计算日期')
    return
  }
  maintenanceScoreDateLoading.value = true
  try {
    const isReset = actionLoading['maintenanceRecord']?.reset
    const result = isReset ? await resetSummaryMaintenanceScore(maintenanceScoreDate.value) : await summaryMaintenanceScore(maintenanceScoreDate.value)
    if (result.data.code === 200) {
      await new Promise(resolve => setTimeout(resolve, 1000))
      await fetchMaintenancePerformanceData()
      await fetchAllPerformanceAbstract()
      ElMessage.success(`维护记录数量绩效${isReset ? '重新计算' : '计算'}完成`)
      maintenanceScoreDateVisible.value = false
    } else {
      ElMessage.error(result.data.msg || `${isReset ? '重新计算' : '计算'}失败`)
    }
  } catch (error) {
    ElMessage.error(`${actionLoading['maintenanceRecord']?.reset ? '重新计算' : '计算'}失败`)
  } finally {
    maintenanceScoreDateLoading.value = false
    calculatingStates['maintenanceRecord'] = false
    if (actionLoading['maintenanceRecord']?.reset) {
      actionLoading['maintenanceRecord'].reset = false
    }
  }
}

// 处理上线测试得分绩效日期选择取消
const handleOnlineTestScoreDateCancel = () => {
  onlineTestScoreDateVisible.value = false
  // 重置加载状态
  calculatingStates['onlineTestScore'] = false
  if (actionLoading['onlineTestScore']?.reset) {
    actionLoading['onlineTestScore'].reset = false
  }
}

// 处理上线测试得分绩效日期选择对话框关闭
const handleOnlineTestScoreDateClose = () => {
  // 重置加载状态
  calculatingStates['onlineTestScore'] = false
  if (actionLoading['onlineTestScore']?.reset) {
    actionLoading['onlineTestScore'].reset = false
  }
}

// 确认上线测试得分绩效日期选择
const confirmOnlineTestScoreDate = async () => {
  if (!onlineTestScoreDate.value) {
    ElMessage.warning('请选择计算日期')
    return
  }
  onlineTestScoreDateLoading.value = true
  try {
    const isReset = actionLoading['onlineTestScore']?.reset
    const result = isReset ? await resetSummaryOnlineTestingScore(onlineTestScoreDate.value) : await summaryOnlineTestingScore(onlineTestScoreDate.value)
    if (result.data.code === 200) {
      await new Promise(resolve => setTimeout(resolve, 1000))
      await fetchOnlineTestPerformanceData()
      await fetchAllPerformanceAbstract()
      ElMessage.success(`上线测试得分绩效${isReset ? '重新计算' : '计算'}完成`)
      onlineTestScoreDateVisible.value = false
    } else {
      ElMessage.error(result.data.msg || `${isReset ? '重新计算' : '计算'}失败`)
    }
  } catch (error) {
    ElMessage.error(`${actionLoading['onlineTestScore']?.reset ? '重新计算' : '计算'}失败`)
  } finally {
    onlineTestScoreDateLoading.value = false
    calculatingStates['onlineTestScore'] = false
    if (actionLoading['onlineTestScore']?.reset) {
      actionLoading['onlineTestScore'].reset = false
    }
  }
}

// 处理用例得分绩效日期选择取消
const handleUseCaseScoreDateCancel = () => {
  useCaseScoreDateVisible.value = false
  // 重置加载状态
  calculatingStates['testCaseScore'] = false
  if (actionLoading['testCaseScore']?.reset) {
    actionLoading['testCaseScore'].reset = false
  }
}

// 处理用例得分绩效日期选择对话框关闭
const handleUseCaseScoreDateClose = () => {
  // 重置加载状态
  calculatingStates['testCaseScore'] = false
  if (actionLoading['testCaseScore']?.reset) {
    actionLoading['testCaseScore'].reset = false
  }
}

// 确认用例得分绩效日期选择
const confirmUseCaseScoreDate = async () => {
  if (!useCaseScoreDate.value) {
    ElMessage.warning('请选择计算日期')
    return
  }
  useCaseScoreDateLoading.value = true
  try {
    const isReset = actionLoading['testCaseScore']?.reset
    const result = isReset ? await resetSummaryUseCaseScore(useCaseScoreDate.value) : await summaryUseCaseScore(useCaseScoreDate.value)
    if (result.data.code === 200) {
      await new Promise(resolve => setTimeout(resolve, 1000))
      await fetchUseCasePerformanceData()
      await fetchAllPerformanceAbstract()
      ElMessage.success(`用例得分绩效${isReset ? '重新计算' : '计算'}完成`)
      useCaseScoreDateVisible.value = false
    } else {
      ElMessage.error(result.data.msg || `${isReset ? '重新计算' : '计算'}失败`)
    }
  } catch (error) {
    ElMessage.error(`${actionLoading['testCaseScore']?.reset ? '重新计算' : '计算'}失败`)
  } finally {
    useCaseScoreDateLoading.value = false
    calculatingStates['testCaseScore'] = false
    if (actionLoading['testCaseScore']?.reset) {
      actionLoading['testCaseScore'].reset = false
    }
  }
}

// 处理沟通协调得分绩效日期选择取消
const handleCommunicationScoreDateCancel = () => {
  communicationScoreDateVisible.value = false
  // 重置加载状态
  calculatingStates['communication'] = false
  if (actionLoading['communication']?.reset) {
    actionLoading['communication'].reset = false
  }
}

// 处理沟通协调得分绩效日期选择对话框关闭
const handleCommunicationScoreDateClose = () => {
  // 重置加载状态
  calculatingStates['communication'] = false
  if (actionLoading['communication']?.reset) {
    actionLoading['communication'].reset = false
  }
}

// 确认沟通协调得分绩效日期选择
const confirmCommunicationScoreDate = async () => {
  if (!communicationScoreDate.value) {
    ElMessage.warning('请选择计算日期')
    return
  }
  communicationScoreDateLoading.value = true
  try {
    const isReset = actionLoading['communication']?.reset
    const result = isReset ? await resetSummaryCommunicationScore(communicationScoreDate.value) : await summaryCommunicationScore(communicationScoreDate.value)
    if (result.data.code === 200) {
      await new Promise(resolve => setTimeout(resolve, 1000))
      await fetchCommunicationPerformanceData()
      await fetchAllPerformanceAbstract()
      ElMessage.success(`沟通协调得分绩效${isReset ? '重新计算' : '计算'}完成`)
      communicationScoreDateVisible.value = false
    } else {
      ElMessage.error(result.data.msg || `${isReset ? '重新计算' : '计算'}失败`)
    }
  } catch (error) {
    ElMessage.error(`${actionLoading['communication']?.reset ? '重新计算' : '计算'}失败`)
  } finally {
    communicationScoreDateLoading.value = false
    calculatingStates['communication'] = false
    if (actionLoading['communication']?.reset) {
      actionLoading['communication'].reset = false
    }
  }
}

// 处理差的日报绩效日期选择取消
const handlePoorDailyReportDateCancel = () => {
  poorDailyReportDateVisible.value = false
  // 重置加载状态
  calculatingStates['poorDailyReport'] = false
  if (actionLoading['poorDailyReport']?.reset) {
    actionLoading['poorDailyReport'].reset = false
  }
}

// 处理差的日报绩效日期选择对话框关闭
const handlePoorDailyReportDateClose = () => {
  // 重置加载状态
  calculatingStates['poorDailyReport'] = false
  if (actionLoading['poorDailyReport']?.reset) {
    actionLoading['poorDailyReport'].reset = false
  }
}

// 确认差的日报绩效日期选择
const confirmPoorDailyReportDate = async () => {
  if (!poorDailyReportDate.value) {
    ElMessage.warning('请选择计算日期')
    return
  }
  poorDailyReportDateLoading.value = true
  try {
    const isReset = actionLoading['poorDailyReport']?.reset
    const result = isReset ? await resetSummaryItemPoorDailyReports(poorDailyReportDate.value) : await summaryItemPoorDailyReports(poorDailyReportDate.value)
    if (result.data.code === 200) {
      await new Promise(resolve => setTimeout(resolve, 1000))
      await fetchPoorDailyReportPerformanceData()
      await fetchAllPerformanceAbstract()
      ElMessage.success(`差的日报绩效${isReset ? '重新计算' : '计算'}完成`)
      poorDailyReportDateVisible.value = false
    } else {
      ElMessage.error(result.data.msg || `${isReset ? '重新计算' : '计算'}失败`)
    }
  } catch (error) {
    ElMessage.error(`${actionLoading['poorDailyReport']?.reset ? '重新计算' : '计算'}失败`)
  } finally {
    poorDailyReportDateLoading.value = false
    calculatingStates['poorDailyReport'] = false
    if (actionLoading['poorDailyReport']?.reset) {
      actionLoading['poorDailyReport'].reset = false
    }
  }
}

// 处理日报重复率绩效日期选择取消
const handleDailyReportRepetitionDateCancel = () => {
  dailyReportRepetitionDateVisible.value = false
  // 重置加载状态
  calculatingStates['dailyReportRepetition'] = false
  if (actionLoading['dailyReportRepetition']?.reset) {
    actionLoading['dailyReportRepetition'].reset = false
  }
}

// 处理日报重复率绩效日期选择对话框关闭
const handleDailyReportRepetitionDateClose = () => {
  // 重置加载状态
  calculatingStates['dailyReportRepetition'] = false
  if (actionLoading['dailyReportRepetition']?.reset) {
    actionLoading['dailyReportRepetition'].reset = false
  }
}

// 确认日报重复率绩效日期选择
const confirmDailyReportRepetitionDate = async () => {
  if (!dailyReportRepetitionDate.value) {
    ElMessage.warning('请选择计算日期')
    return
  }
  dailyReportRepetitionDateLoading.value = true
  try {
    const isReset = actionLoading['dailyReportRepetition']?.reset
    const result = isReset ? await resetSummaryItemDailyReportRepetitionRate(dailyReportRepetitionDate.value) : await summaryItemDailyReportRepetitionRate(dailyReportRepetitionDate.value)
    if (result.data.code === 200) {
      await new Promise(resolve => setTimeout(resolve, 1000))
      await fetchDailyReportRepetitionPerformanceData()
      await fetchAllPerformanceAbstract()
      ElMessage.success(`日报重复率绩效${isReset ? '重新计算' : '计算'}完成`)
      dailyReportRepetitionDateVisible.value = false
    } else {
      ElMessage.error(result.data.msg || `${isReset ? '重新计算' : '计算'}失败`)
    }
  } catch (error) {
    ElMessage.error(`${actionLoading['dailyReportRepetition']?.reset ? '重新计算' : '计算'}失败`)
  } finally {
    dailyReportRepetitionDateLoading.value = false
    calculatingStates['dailyReportRepetition'] = false
    if (actionLoading['dailyReportRepetition']?.reset) {
      actionLoading['dailyReportRepetition'].reset = false
    }
  }
}

// 处理上线运维得分绩效日期选择取消
const handleOnlineOperationScoreDateCancel = () => {
  onlineOperationScoreDateVisible.value = false
  // 重置加载状态
  calculatingStates['onlineOperation'] = false
  if (actionLoading['onlineOperation']?.reset) {
    actionLoading['onlineOperation'].reset = false
  }
}

// 处理上线运维得分绩效日期选择对话框关闭
const handleOnlineOperationScoreDateClose = () => {
  // 重置加载状态
  calculatingStates['onlineOperation'] = false
  if (actionLoading['onlineOperation']?.reset) {
    actionLoading['onlineOperation'].reset = false
  }
}

// 确认上线运维得分绩效日期选择
const confirmOnlineOperationScoreDate = async () => {
  if (!onlineOperationScoreDate.value) {
    ElMessage.warning('请选择计算日期')
    return
  }
  onlineOperationScoreDateLoading.value = true
  try {
    const isReset = actionLoading['onlineOperation']?.reset
    const result = isReset ? await resetOnlineOperationScore(onlineOperationScoreDate.value) : await summaryOnlineOperationScore(onlineOperationScoreDate.value)
    if (result.data.code === 200) {
      await new Promise(resolve => setTimeout(resolve, 1000))
      await fetchOnlineOperationPerformanceData()
      await fetchAllPerformanceAbstract()
      ElMessage.success(`上线运维得分绩效${isReset ? '重新计算' : '计算'}完成`)
      onlineOperationScoreDateVisible.value = false
    } else {
      ElMessage.error(result.data.msg || `${isReset ? '重新计算' : '计算'}失败`)
    }
  } catch (error) {
    ElMessage.error(`${actionLoading['onlineOperation']?.reset ? '重新计算' : '计算'}失败`)
  } finally {
    onlineOperationScoreDateLoading.value = false
    calculatingStates['onlineOperation'] = false
    if (actionLoading['onlineOperation']?.reset) {
      actionLoading['onlineOperation'].reset = false
    }
  }
}

// 弹窗标题
const currentDetailTitle = computed(() => {
  const item = performanceItems.value.find(i => i.key === currentDetailType.value)
  return item ? `${item.name}数据` : '绩效数据'
})

// 处理WIKI得分绩效日期选择取消
const handleWikiScoreDateCancel = () => {
  wikiScoreDateVisible.value = false
  // 重置加载状态
  calculatingStates['wikiScore'] = false
  if (actionLoading['wikiScore']?.reset) {
    actionLoading['wikiScore'].reset = false
  }
}

// 处理WIKI得分绩效日期选择对话框关闭
const handleWikiScoreDateClose = () => {
  // 重置加载状态
  calculatingStates['wikiScore'] = false
  if (actionLoading['wikiScore']?.reset) {
    actionLoading['wikiScore'].reset = false
  }
}

// 确认WIKI得分绩效日期选择
const confirmWikiScoreDate = async () => {
  if (!wikiScoreDate.value) {
    ElMessage.warning('请选择计算日期')
    return
  }
  
  wikiScoreDateLoading.value = true
  try {
    // 判断是计算还是重新计算
    const isReset = actionLoading['wikiScore']?.reset
    const result = isReset ? await resetSummaryWikiScore(wikiScoreDate.value) : await summaryWikiScore(wikiScoreDate.value)
    
    if (result.data.code === 200) {
      // 等待一下让后端数据处理完成
      await new Promise(resolve => setTimeout(resolve, 1000))
      await fetchWikiPerformanceData()
      await fetchAllPerformanceAbstract()
      ElMessage.success(`WIKI得分绩效${isReset ? '重新计算' : '计算'}完成`)
      wikiScoreDateVisible.value = false
    } else {
      ElMessage.error(result.data.msg || `${isReset ? '重新计算' : '计算'}失败`)
    }
  } catch (error) {
    ElMessage.error(`${actionLoading['wikiScore']?.reset ? '重新计算' : '计算'}失败`)
  } finally {
    wikiScoreDateLoading.value = false
    calculatingStates['wikiScore'] = false
    if (actionLoading['wikiScore']?.reset) {
      actionLoading['wikiScore'].reset = false
    }
  }
}

// 获取工作量得分绩效数据
const fetchWorkloadPerformanceData = async () => {
  detailsLoading.value = true
  try {
    const result = await getSummaryWorkloadScore()
    if (result.data && result.data.code === 200) {
      const list = Array.isArray(result.data.data) ? result.data.data : []
      if (list.length > 0) {
        const normalizedList = list.map((it: any) => ({
          ...it,
          userName: it.userName ?? it.versionUserName,
          score: it.score ?? it.rankNumber,
          scoreRank: it.scoreRank ?? it.rankRanking
        }))
        const firstItem = normalizedList[0]
        const standardData = {
          recentDate: firstItem.versionDate,
          position: firstItem.versionPost,
          employeeName: firstItem.versionUserName,
          positionCoefficient: firstItem.jobXs,
          baseCoefficient: firstItem.jobXsjc,
          basePerformance: firstItem.basePerformance,
          scoreRank: firstItem.rankRanking,
          performanceScore: firstItem.rankScore,
          score: firstItem.rankNumber,
          performanceType: firstItem.levelType,
          rawData: normalizedList
        }
        performanceData['workloadScore'] = standardData
      } else {
        delete performanceData['workloadScore']
        await fetchAllPerformanceAbstract()
      }
    } else {
      ElMessage.error('获取工作量得分绩效数据失败')
    }
  } catch (error) {
    ElMessage.error('获取工作量得分绩效数据失败')
  }
  detailsLoading.value = false
}

// 获取汇报材料得分绩效数据
const fetchReportMaterialPerformanceData = async () => {
  detailsLoading.value = true
  try {
    const result = await getSummaryReportMaterialScore()
    if (result.data && result.data.code === 200) {
      const list = Array.isArray(result.data.data) ? result.data.data : []
      if (list.length > 0) {
        const normalizedList = list.map((it: any) => ({
          ...it,
          userName: it.userName ?? it.versionUserName,
          score: it.score ?? it.rankNumber,
          scoreRank: it.scoreRank ?? it.rankRanking
        }))
        const firstItem = normalizedList[0]
        const standardData = {
          recentDate: firstItem.versionDate,
          position: firstItem.versionPost,
          employeeName: firstItem.versionUserName,
          positionCoefficient: firstItem.jobXs,
          baseCoefficient: firstItem.jobXsjc,
          basePerformance: firstItem.basePerformance,
          scoreRank: firstItem.rankRanking,
          performanceScore: firstItem.rankScore,
          score: firstItem.rankNumber,
          performanceType: firstItem.levelType,
          rawData: normalizedList
        }
        performanceData['reportMaterial'] = standardData
      } else {
        delete performanceData['reportMaterial']
        await fetchAllPerformanceAbstract()
      }
    } else {
      ElMessage.error('获取汇报材料得分绩效数据失败')
    }
  } catch (error) {
    ElMessage.error('获取汇报材料得分绩效数据失败')
  }
  detailsLoading.value = false
}

// 处理汇报材料得分绩效日期选择取消
const handleReportMaterialScoreDateCancel = () => {
  reportMaterialScoreDateVisible.value = false
  calculatingStates['reportMaterial'] = false
  if (actionLoading['reportMaterial']?.reset) {
    actionLoading['reportMaterial'].reset = false
  }
}

// 处理汇报材料得分绩效日期选择对话框关闭
const handleReportMaterialScoreDateClose = () => {
  calculatingStates['reportMaterial'] = false
  if (actionLoading['reportMaterial']?.reset) {
    actionLoading['reportMaterial'].reset = false
  }
}

// 确认汇报材料得分绩效日期选择
const confirmReportMaterialScoreDate = async () => {
  if (!reportMaterialScoreDate.value) {
    ElMessage.warning('请选择计算日期')
    return
  }
  reportMaterialScoreDateLoading.value = true
  try {
    const isReset = actionLoading['reportMaterial']?.reset
    const result = isReset ? await resetSummaryReportMaterialScore(reportMaterialScoreDate.value) : await summaryReportMaterialScore(reportMaterialScoreDate.value)
    if (result.data.code === 200) {
      await new Promise(resolve => setTimeout(resolve, 1000))
      await fetchReportMaterialPerformanceData()
      await fetchAllPerformanceAbstract()
      ElMessage.success(`汇报材料得分绩效${isReset ? '重新计算' : '计算'}完成`)
      reportMaterialScoreDateVisible.value = false
    } else {
      ElMessage.error(result.data.msg || `${isReset ? '重新计算' : '计算'}失败`)
    }
  } catch (error) {
    ElMessage.error(`${actionLoading['reportMaterial']?.reset ? '重新计算' : '计算'}失败`)
  } finally {
    reportMaterialScoreDateLoading.value = false
    calculatingStates['reportMaterial'] = false
    if (actionLoading['reportMaterial']?.reset) {
      actionLoading['reportMaterial'].reset = false
    }
  }
}

// 处理工作量得分绩效日期选择取消
const handleWorkloadScoreDateCancel = () => {
  workloadScoreDateVisible.value = false
  // 重置加载状态
  calculatingStates['workloadScore'] = false
  if (actionLoading['workloadScore']?.reset) {
    actionLoading['workloadScore'].reset = false
  }
}

// 处理工作量得分绩效日期选择对话框关闭
const handleWorkloadScoreDateClose = () => {
  // 重置加载状态
  calculatingStates['workloadScore'] = false
  if (actionLoading['workloadScore']?.reset) {
    actionLoading['workloadScore'].reset = false
  }
}

// 确认工作量得分绩效日期选择
const confirmWorkloadScoreDate = async () => {
  if (!workloadScoreDate.value) {
    ElMessage.warning('请选择计算日期')
    return
  }
  workloadScoreDateLoading.value = true
  try {
    const isReset = actionLoading['workloadScore']?.reset
    const result = isReset ? await resetSummaryWorkloadScore(workloadScoreDate.value) : await summaryWorkloadScore(workloadScoreDate.value)
    if (result.data.code === 200) {
      await new Promise(resolve => setTimeout(resolve, 1000))
      await fetchWorkloadPerformanceData()
      await fetchAllPerformanceAbstract()
      ElMessage.success(`工作量得分绩效${isReset ? '重新计算' : '计算'}完成`)
      workloadScoreDateVisible.value = false
    } else {
      ElMessage.error(result.data.msg || `${isReset ? '重新计算' : '计算'}失败`)
    }
  } catch (error) {
    ElMessage.error(`${actionLoading['workloadScore']?.reset ? '重新计算' : '计算'}失败`)
  } finally {
    workloadScoreDateLoading.value = false
    calculatingStates['workloadScore'] = false
    if (actionLoading['workloadScore']?.reset) {
      actionLoading['workloadScore'].reset = false
    }
  }
}

// 获取出差得分绩效数据
const fetchBusinessTripPerformanceData = async () => {
  detailsLoading.value = true
  try {
    const result = await getSummaryBusinessTripScore()
    if (result.data && result.data.code === 200) {
      const list = Array.isArray(result.data.data) ? result.data.data : []
      if (list.length > 0) {
        const normalizedList = list.map((it: any) => ({
          ...it,
          userName: it.userName ?? it.versionUserName,
          score: it.score ?? it.rankNumber,
          scoreRank: it.scoreRank ?? it.rankRanking
        }))
        const firstItem = normalizedList[0]
        const standardData = {
          recentDate: firstItem.versionDate,
          position: firstItem.versionPost,
          employeeName: firstItem.versionUserName,
          positionCoefficient: firstItem.jobXs,
          baseCoefficient: firstItem.jobXsjc,
          basePerformance: firstItem.basePerformance,
          scoreRank: firstItem.rankRanking,
          performanceScore: firstItem.rankScore,
          score: firstItem.rankNumber,
          performanceType: firstItem.levelType,
          rawData: normalizedList
        }
        performanceData['businessTrip'] = standardData
      } else {
        delete performanceData['businessTrip']
        await fetchAllPerformanceAbstract()
      }
    } else {
      ElMessage.error('获取出差得分绩效数据失败')
    }
  } catch (error) {
    ElMessage.error('获取出差得分绩效数据失败')
  }
  detailsLoading.value = false
}

// 处理出差得分绩效日期选择取消
const handleBusinessTripScoreDateCancel = () => {
  businessTripScoreDateVisible.value = false
  calculatingStates['businessTrip'] = false
  if (actionLoading['businessTrip']?.reset) {
    actionLoading['businessTrip'].reset = false
  }
}

// 处理出差得分绩效日期选择对话框关闭
const handleBusinessTripScoreDateClose = () => {
  calculatingStates['businessTrip'] = false
  if (actionLoading['businessTrip']?.reset) {
    actionLoading['businessTrip'].reset = false
  }
}

// 确认出差得分绩效日期选择
const confirmBusinessTripScoreDate = async () => {
  if (!businessTripScoreDate.value) {
    ElMessage.warning('请选择计算日期')
    return
  }
  businessTripScoreDateLoading.value = true
  try {
    const isReset = actionLoading['businessTrip']?.reset
    const result = isReset ? await resetSummaryBusinessTripScore(businessTripScoreDate.value) : await summaryBusinessTripScore(businessTripScoreDate.value)
    if (result.data.code === 200) {
      await new Promise(resolve => setTimeout(resolve, 1000))
      await fetchBusinessTripPerformanceData()
      await fetchAllPerformanceAbstract()
      ElMessage.success(`出差得分绩效${isReset ? '重新计算' : '计算'}完成`)
      businessTripScoreDateVisible.value = false
    } else {
      ElMessage.error(result.data.msg || `${isReset ? '重新计算' : '计算'}失败`)
    }
  } catch (error) {
    ElMessage.error(`${actionLoading['businessTrip']?.reset ? '重新计算' : '计算'}失败`)
  } finally {
    businessTripScoreDateLoading.value = false
    calculatingStates['businessTrip'] = false
    if (actionLoading['businessTrip']?.reset) {
      actionLoading['businessTrip'].reset = false
    }
  }
}
</script>

<style scoped>
.performance-page {
  padding: 20px 20px 100px 20px; /* 进一步增加底部内边距，确保最后一个卡片完整显示 */
  background-color: #f5f5f5;
  /* 设置固定高度，支持滚动但不显示滚动条 */
  height: 100vh;
  max-height: 100vh;
  overflow-y: auto; /* 允许垂直滚动 */
  overflow-x: hidden; /* 隐藏水平滚动条 */
  /* 改进滚动行为 */
  scroll-behavior: smooth;
  -webkit-overflow-scrolling: touch; /* iOS 平滑滚动 */
  /* 确保容器可以滚动 */
  position: relative;
  box-sizing: border-box;
}

/* 隐藏所有浏览器的滚动条 */
.performance-page::-webkit-scrollbar {
  width: 0px; /* 隐藏 WebKit 滚动条 */
  background: transparent;
}

.performance-page::-webkit-scrollbar-track {
  background: transparent;
}

.performance-page::-webkit-scrollbar-thumb {
  background: transparent;
}

/* Firefox 隐藏滚动条 */
.performance-page {
  scrollbar-width: none !important;
  -ms-overflow-style: none !important; /* IE/Edge 隐藏滚动条 */
}





/* 顶部页眉已移除 */

.performance-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(450px, 1fr));
  gap: 20px;
  /* 确保网格容器有足够的空间 */
  width: 100%;
  box-sizing: border-box;
}

.performance-item {
  background: white;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  transition: transform 0.2s ease;
}

.performance-item.fault-deduction {
  background: linear-gradient(135deg, #fff9f0 0%, #fff5e6 100%);
  border: 2px solid #e6a23c;
  box-shadow: 0 4px 12px rgba(230, 162, 60, 0.15);
}

.performance-item.fault-deduction:hover {
  transform: translateY(-3px);
  box-shadow: 0 6px 20px rgba(230, 162, 60, 0.25);
}

.performance-item:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.15);
}

.item-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 15px;
  padding-bottom: 10px;
  border-bottom: 1px solid #eee;
  gap: 15px;
}

.title-section {
  flex: 1;
  min-width: 0;
}

.item-header h3 {
  margin: 0;
  color: #333;
  font-size: 16px;
  line-height: 1.4;
  word-wrap: break-word;
  overflow-wrap: break-word;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  cursor: help;
}

.item-description {
  margin: 6px 0 0 0;
  color: #e6a23c;
  font-size: 13px;
  line-height: 1.4;
  font-weight: 500;
  background: rgba(230, 162, 60, 0.1);
  padding: 6px 10px;
  border-radius: 6px;
  border-left: 3px solid #e6a23c;
  position: relative;
}

.item-description::before {
  content: "⚠️";
  margin-right: 6px;
  font-size: 14px;
}

.button-group {
  display: flex;
  gap: 8px;
  flex-shrink: 0;
  flex-wrap: nowrap;
  min-width: 70px;
}

.action-btn {
  min-width: 60px;
  padding: 8px 12px;
  font-size: 12px;
}

.performance-result {
  margin-top: 15px;
}

.abstract-summary {
  margin-top: 10px;
}

.performance-result :deep(.el-descriptions) {
  margin-top: 10px;
}

.performance-result :deep(.el-descriptions__label) {
  font-weight: 600;
  color: #333;
}

.performance-result :deep(.el-descriptions__content) {
  color: #666;
}

/* 中等屏幕尺寸优化 */
@media (max-width: 1024px) and (min-width: 769px) {
  .performance-grid {
    grid-template-columns: repeat(auto-fit, minmax(400px, 1fr));
    gap: 18px;
  }
}

@media (max-width: 768px) {
  .performance-page {
    padding: 15px 15px 60px 15px; /* 移动端调整内边距 */
  }
  
  .performance-grid {
    grid-template-columns: 1fr;
    gap: 15px; /* 移动端减少间距 */
  }
  
  
  

  .item-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }

  .title-section {
    width: 100%;
  }

  .item-header h3 {
    white-space: normal;
    text-overflow: clip;
  }

  .button-group {
    width: 100%;
    justify-content: flex-start;
    flex-wrap: wrap;
  }

  .button-group .el-button {
    flex: 1;
    min-width: 120px;
  }

  .header-actions {
    flex-direction: column;
    align-items: center;
  }

  .header-actions .el-button {
    width: 100%;
    max-width: 200px;
  }
}

/* 统计面板样式已移除 */

/* 产品绩效摘要样式 */
.product-summary {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.view-details-btn {
  display: flex;
  justify-content: center;
  margin-top: 10px;
}

/* 模态框样式 */
.dialog-header {
  position: sticky;
  top: 0;
  z-index: 2;
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
  padding: 14px 8px;
  background: linear-gradient(180deg, rgba(255,255,255,0.95), rgba(255,255,255,1));
  border-bottom: 1px solid #e4e7ed;
  box-shadow: 0 2px 6px rgba(0,0,0,0.04);
}

.dialog-header h3 {
  margin: 0;
  color: #333;
  font-size: 18px;
}

.dialog-actions {
  display: flex;
  align-items: center;
  gap: 8px;
}

.toolbar-input { width: 160px; }
.toolbar-switch { margin: 0 6px; }

/* 产品绩效数据表格样式 */
.product-performance-table { width: 100%; }

:deep(.product-performance-table .el-table__header th) {
  background: #f5f7fa;
  color: #2c3e50;
  font-weight: 600;
}

:deep(.product-performance-table .el-table__row:hover > td) {
  background-color: #f8fafc !important;
}

:deep(.product-performance-table .el-table__cell) {
  padding: 10px 12px;
}

:deep(.product-performance-table .cell) {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

/* 自定义弹窗整体样式优化 */
:deep(.performance-dialog .el-dialog__header) {
  margin-right: 0;
  padding: 14px 16px 0 16px;
}

:deep(.performance-dialog .el-dialog__title) {
  font-size: 18px;
  font-weight: 600;
  color: #2c3e50;
}

:deep(.performance-dialog .el-dialog__body) {
  padding: 0 16px 16px 16px;
}
:deep(.rank-tag .rank-icon) {
  margin-right: 4px;
}

.name-highlight {
  font-weight: 600;
}

.rank-tag { margin-left: 8px; }

.row-rank-top1 :deep(td) { background: rgba(229, 57, 53, 0.06) !important; }
.row-rank-top2 :deep(td) { background: rgba(251, 140, 0, 0.06) !important; }
.row-rank-top3 :deep(td) { background: rgba(67, 160, 71, 0.06) !important; }

.name-top1 {
  color: #e53935;
}

.name-top2 {
  color: #fb8c00;
}

.name-top3 {
  color: #43a047;
}

/* 排名徽章样式 */
.rank-badge {
  display: inline-flex;
  align-items: center;
  gap: 4px;
  padding: 3px 8px;
  border-radius: 999px;
  font-weight: 600;
  line-height: 1;
  min-width: 44px;
  justify-content: center;
}
.rank-badge__icon { font-size: 14px; }
.rank-badge--gold {
  color: #8a5800;
  background: linear-gradient(180deg, #ffe29a, #ffd166);
  box-shadow: inset 0 0 0 1px rgba(255, 193, 7, 0.35);
}
.rank-badge--silver {
  color: #4b5563;
  background: linear-gradient(180deg, #e5e7eb, #d1d5db);
  box-shadow: inset 0 0 0 1px rgba(107, 114, 128, 0.25);
}
.rank-badge--bronze {
  color: #6b3e1e;
  background: linear-gradient(180deg, #f6cfab, #eab893);
  box-shadow: inset 0 0 0 1px rgba(234, 179, 8, 0.25);
}
.rank-badge--normal {
  color: #374151;
  background: #f3f4f6;
  box-shadow: inset 0 0 0 1px rgba(156, 163, 175, 0.25);
}

/* 弹窗尺寸优化：桌面 70% 宽度，最大 1200px；移动端更贴合 */
:deep(.performance-dialog .el-dialog) {
  max-width: 1200px;
}

@media (max-width: 768px) {
  :deep(.performance-dialog .el-dialog) {
    width: 96% !important;
  }
}

/* 移动端适配 */
@media (max-width: 768px) {
  .dialog-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }
}

/* WIKI得分绩效日期选择样式 */
.date-selection {
  padding: 20px 0;
}
</style>
